0

我正在测试 Ray Wenderlich 的代码以从 URL 下载数据。我让它工作了,但我更新到 Xcode 8.3,现在突然它不再工作了。我得到的建议是,我的问题已经在以下链接SWIFT: Error EXC_BAD_INSTRUCTION中得到解决,但是,在添加尝试时!选项或按照建议添加一个 do-catch,这并没有使错误消失。这是代码:

class func loadDataFromURL(_ url: URL, completion:@escaping (_ data: Data?, _ error: NSError?) -> Void) {


            let session = URLSession.shared
                // Use NSURLSession to get data from an NSURL



            let loadDataTask = try! session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
              if let responseError = error {
                completion(nil, responseError)
                print("something went wrong 1")

                //activityIndicator.stopAnimating()
              } else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode != 200 {
                 let statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
                  completion(nil, statusError)
                } else {
                  completion(data, nil)
                    //activityIndicator.stopAnimating()
                }
              }

            } as! (Data?, URLResponse?, Error?) -> Void)  //error is thrown here!!

        loadDataTask.resume()     
}
}

当我运行代码时,我在最后一行得到错误代码:“线程 1:EXEC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)”

4

1 回答 1

0

当我尝试异步解析数据时遇到了这个问题,它消除了错误并且工作正常。我不确定,但它也可以解决你的问题。

于 2017-04-13T00:32:57.513 回答