jamie jamie - 5 months ago 57
Swift Question

Swift add params to request

I'm trying to add an email and a password to a

NSURLSession
request
like this:

@IBAction func btnLogin(sender: AnyObject) {
let email = txtEmail.text
let password = txtPassword.text
let data = ["email": email!, "password": password!] as Dictionary<String, String>
let session = NSURLSession.sharedSession()
let url = NSURL(string: "http://temp.com/api/v1/login")!
let request = NSMutableURLRequest(URL: url)
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(data, options: [])
}
catch {
print("error!")
}
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
guard let response = response as? NSHTTPURLResponse else {print(error); return}
if response.statusCode == 200 {
print("ingelogd!")
}
self.errorLogin()
}
task.resume()
}


error:

2016-07-03 17:54:04.890 EmployeeDirectory2[4693:133721] *** Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.60.7/Keyboard/UIKeyboardTaskQueue.m:386
2016-07-03 17:54:04.894 EmployeeDirectory2[4693:133721] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'


But when I try this it crashes. How can I add parameters appropriately?

Answer

The crash is probably coming from the call to self.errorLogin() call, which tries to do some UI task outside the main thread. You should be able to fix it like this:

let task = session.dataTaskWithRequest(request) {
    (data, response, error) in
    guard let response = response as? NSHTTPURLResponse else {print(error); return}
    if response.statusCode == 200 {
        print("ingelogd!")
    }
    // Add this:
    dispatch_async(dispatch_get_main_queue()) {
        self.errorLogin()
    }
 }