ios - NSURLConnection 不调用方法(第一次工作)

标签 ios json swift nsurlconnection

所以我使用 NSURLConnection 从网站获取 JSON 数据,它有效,我将数据存储在搜索 Controller / TableView 中。现在,当用户单击 View 中的单元格时,我想转到一个新 View ,并从网站加载另一组 JSON 数据。但是,在这个新 View 中,连接从不运行这些方法。这是我两次都在做的事情(每次都在不同的 View Controller 中)

func startConnection(){
    var url: NSURL = NSURL(string: self.formatted)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
    connection.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) // I tried to put this in based on suggestions from searches I did, it didn't help
    connection.start()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data)

}

func connectionDidFinishLoading(connection: NSURLConnection!){
    var err: NSError
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
    println(jsonResult)

}

从断点看它似乎永远不会运行:

func connection(connection: NSURLConnection!, didReceiveData data: NSData!)

我在 ViewDidLoad 中调用 startConnection()

最佳答案

实现connection:didFailWithError: , 也。看看它报道了什么。否则,您无法知道失败的原因。

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    println("connection error = \(error)")
}

此外,在 didReceiveData(以及其他这些方法)中,NSURLConnection 参数不是可选的。在这些被审计之前,他们可能使用了隐式解包的可选值,但现在不再使用了。仔细检查您的方法签名。如果您实际上将您的类定义为明确符合 NSURLConnectionDataDelegateNSURLConnectionDelegate,您应该收到有关此的警告。


顺便说一句,您没有在 connectionDidFinishLoading 中使用 NSError 变量,如果 JSONObjectWithData 在解析响应时遇到任何问题,则可以填充该变量。因此,将 NSError 变量提供给 JSONObjectWithData,您现在可以诊断解析过程中发生的任何错误。希望你不会有任何解析错误,但如果你这样做了,NSError 引用将非常有用。

此外,您不需要 falsestartImmediately 并在主运行循环上手动安排它。仅当您从后台线程启动此连接时才这样做。但由于您是从 viewDidLoad 调用它,所以这是不必要的。

所以它最终可能看起来像:

func startConnection() {
    data = NSMutableData()
    let url = NSURL(string: formatted)
    let request = NSURLRequest(URL: url!)
    NSURLConnection(request: request, delegate: self)
}

func connection(connection: NSURLConnection, didReceiveData data: NSData) {
    self.data.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection) {
    var error: NSError?
    if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSDictionary {
        println(jsonResult)
    } else {
        println("parsing error = \(error)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)")
    }
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    println("connection error = \(error)")
}

顺便说一句,您可能还想实现 didReceiveResponse,因为它还可以提供有关您可能收到的任何服务器错误的信息:

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    if let httpResponse = response as? NSHTTPURLResponse {
        let statusCode = httpResponse.statusCode

        if statusCode != 200 {
            println("expected HTTP response of 200; received \(statusCode)")
            println(httpResponse)
        }
    } else {
        println("expected HTTP response; but didn't get any")
    }
}

关于ios - NSURLConnection 不调用方法(第一次工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30700249/

相关文章:

ios - OPENGLES 2.0 PUSHMATRIX POP MATRIX 实现

objective-c - 如何加密或混淆 Objective-C 代码?

java - Spring Integration 4.2 中 application/json 响应被转义的问题

jquery - $.getJSON 语法问题

php - `header("的用法 Content-type :application/json");`

swift - 如何将值从 EnvironmentObject 传递到 SwiftUI 中的类实例?

ios - 如何在 Swift 中随机转至 ViewControllers?

ios - 自定义 View 在 ScrollView 内滚动

ios - 如何使用 NSURLSession 下载多个文件

json - 我从 jsonSerialization 中获取转义字符,但无法在 Swift 中对其进行解码