App突然崩溃加载网址

时间:2017-01-27 11:20:19

标签: ios swift swift3 nsurlsessiondatatask

我有以下功能来加载数据。这个功能在几天前​​工作得很好。该应用程序崩溃尝试加载任何网址,请参阅下面的代码和截图。一年只有几天编码ios / swift,很难弄清楚出了什么问题......

API

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 = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
  if let responseError = error {
    completion(nil, responseError)
  } else if let httpResponse = response as? HTTPURLResponse {
    if httpResponse.statusCode != 200 {
      let statusError = NSError(domain:"com.xyz", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
      completion(nil, statusError)
    } else {
      completion(data, nil)
    }
  }
} as! (Data?, URLResponse?, Error?) -> Void)

loadDataTask.resume()
}

1 个答案:

答案 0 :(得分:1)

使用以下代码和最新的Swift 3.0语法,它适用于Xcode 8.2: -

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 = session.dataTask(with: url) { (data, response, error) in
            if let responseError = error {
                completion(nil, responseError as NSError?)
            } else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode != 200 {
                    let statusError = NSError(domain:"com.xyz", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
                    completion(nil, statusError)
                } else {
                    completion(data, nil)
                }
            }
        }
        loadDataTask.resume()

    }