我正在尝试向NSURLSession
request
添加电子邮件和密码,如下所示:
@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()
}
错误:
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.'
但是当我尝试这个时它会崩溃。如何正确添加参数?
答案 0 :(得分:1)
崩溃可能来自对self.errorLogin()
调用的调用,该调用尝试在主线程之外执行一些UI任务。你应该能够像这样解决它:
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()
}
}