POST请求响应后启动segue

时间:2015-08-20 20:40:27

标签: ios swift

我向后端发送POST请求,我在启动segue到下一个视图控制器之前等待响应。什么是最好的方法 - 一些带有完成处理程序的异步块?如果POST请求返回某个值,应用程序应该转到下一个视图控制器,如果响应是错误,则不应发生segue。

@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.'

1 个答案:

答案 0 :(得分:0)

看起来完成处理程序是从不是主线程的线程调用的。要确保在主线程上执行完成处理程序,请将调用包装到在主线程上执行的gcd块内的完成处理程序:

dispatch_async(dispatch_get_main_queue()) {
    completion(result:true)
}