1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Julia
  • 1,207
  • 4
  • 29
  • 47
  • The EXC_BAD_INSTRUCTION means your `as!` cast failed at runtime. – Lily Ballard Nov 09 '17 at 22:47
  • 1
    Why are you casting your completion handler anyway? There's literally no reason to do that. If the cast works, it's not needed, and if it is needed, it's going to fail at runtime (as you just found out) – Lily Ballard Nov 09 '17 at 22:47
  • Looks like you're casting because your completion handler uses `NSError`? Don't do that. Just use `Error`. – Lily Ballard Nov 09 '17 at 22:48

1 Answers1

1

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
})
vadian
  • 274,689
  • 30
  • 353
  • 361