我正在向后端发送POST请求,并且正在等待响应,然后再向下一个视图控制器启动segue。最好的方法是什么-一些带有完成处理程序的异步块?如果POST请求返回某个值,则应用程序应选择到下一个视图控制器,如果响应为错误,则不应发生选择。
@IBAction func finishPressed(sender: AnyObject) {
if self.emailField.text != "" && self.usernameField.text != "" && self.passwordField.text != ""
{
var dict = ["email": emailField.text, "username": usernameField.text, "password_hash": passwordField.text]
self.register2(dict, completion: { (result) -> Void in
if (result == true)
{
self.performSegueWithIdentifier("homeView", sender: nil)
}
else
{
print("can't segue")
}
})
}
func register(params: Dictionary<String, String!>, completion: (result:Bool) -> Void))
{
//Request set up and configuration
var json = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves, error: &err) as? NSDictionary
if(err != nil)
{
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
completion(result: true)
}
else {
if let parseJSON = json {
var success = parseJSON["success"] as? Int
var usernameError = parseJSON["usernameError"] as? String
var emailError = parseJSON["emailError"] as? String
if success == 1
{
print("we have Success: \(success)")
completion(result: true)
}
else
{
print("we have Failure: \(success)")
completion(result: false)
}
else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
completion(result: false)
}
}
})
task.resume()
}
编辑:我向代码中添加了一个完成处理程序,但尝试segue时其崩溃
*** Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished]
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'
最佳答案
看起来从不是主线程的线程调用了完成处理程序。为确保完成处理程序在主线程上执行,请将对完成处理程序的调用包装在在主线程上执行的gcd块中:
dispatch_async(dispatch_get_main_queue()) {
completion(result:true)
}
关于ios - POST请求响应后启动segue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32127973/