Reputation: 13
the following error appears after running my app and trying to register an user:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_l386_INVOP,s subcode=0x0)
This appears at the end of the code:
} as! (Data?, URLResponse?, Error?) -> Void )
let myUrl = NSURL(string: "http://127.0.0.1/MySQL_PHP/userRegister.php")
var request = URLRequest(url: myUrl as! URL)
request.httpMethod = "POST"
// let config = URLSessionConfiguration.default
let session = URLSession.shared
let postString = "email=\(userEmail)&passwort=\(userPasswort)&vorname=\(userVorname)&nachname=\(userName)&benutzer=\(userBenutzer)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
var json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
if let parseJSON = json {
var resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
var isUserRegistered: Bool = false
if (resultValue == "Success") {
isUserRegistered = true
}
var messageToDisplay: String = parseJSON["message"] as! String!
if (!isUserRegistered){
messageToDisplay = parseJSON["message"] as! String!
}
DispatchQueue.main.async(execute: {
var myAlert = UIAlertController(title:"Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){
action in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
})
}
} as! (Data?, URLResponse?, Error?) -> Void )
task.resume()
Upvotes: 1
Views: 287
Reputation: 285240
The error is misleading. It's not directly related to the data task closure.
First of all do not cast at all
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
...
})
or even still shorter using trailing closure syntax:
let task = session.dataTask(with: request) { (data, response, error) in
...
}
The error occurs because the do - catch
block is missing around try JSONSerialization
The error goes away either by adding the do - catch
block or using try!
And finally a suggestion: Please, please, please do not use NSArray / NSDictionary
in Swift. You are fighting the strong type system.
Upvotes: 2