I'm getting a Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0) after running my code in Xcode 9. The code works fine in Xcode 8.
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:"Domain", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(nil, statusError)
} else {
completion(data, nil)
}
}
} as! (Data?, URLResponse?, Error?) -> Void) //Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0)
loadDataTask.resume()
}
I'm trying to load data from an url, I don't know why I am getting this error. Thank you.
Don't forced cast, just use the proper syntax, no type annotation in the closure and no type cast at the end:
let loadDataTask = session.dataTask(with: url, completionHandler: { (data, response, error) in
// code
})