Search code examples
iosswiftswift3nsurlsessiondatatask

App sudden crash loading url


I have the following function to load data. The function worked just fine till a couple of days ago. The app crashes trying to load any url, see code below and screenshot. Coding ios/swift just a few days a year, it pretty hard to figure out what's wrong...

enter image description here

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()
}

Solution

  • Use below code with latest Swift 3.0 syntax it works on 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()
    
        }