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

NSURLConnection not calling methods (worked the first time)

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

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 参数不是可选的。在这些被审计之前,他们可能使用了隐式解包的可选值,但现在不再使用了。仔细检查您的方法签名。如果您实际上将 class 定义为明确符合 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")
    }
}