ios - waitUntilAllTask​​sAreFinished 错误 Swift

按下提交按钮时,我的 loginViewController 中有此调用:

let http = HTTPHelper()
    http.post("http://someUrl.com/Login/userEmail/\(username.text)/Pswd/\(userPass.text)", postCompleted: self.checkLogin)

虽然我发送的 checkLogin 功能只是在执行:

func checkLogin(succeed: Bool, msg: String){
    if (succeed){
        self.performSegueWithIdentifier("logInTrue", sender: self)
    }
}

post 函数是 HTTPHelper 类是:

func post(url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    var err: NSError?
     self.task = session.dataTaskWithURL(NSURL(string: url)!)  {(data, response, error) in
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &err) as? NSDictionary
        var msg = "No message"
        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            postCompleted(succeeded: false, msg: "Error")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                if let success = parseJSON["result"] as? Bool {
                    postCompleted(succeeded: success, msg: "Logged in.")
                }
                return
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                postCompleted(succeeded: false, msg: "Error")
            }
        }
    }

    self.task!.resume()
}

当 checkLogin 函数被成功调用时:true 它无法执行SegueWithIdentified 函数.. 错误看起来像:

Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished], /SourceCache/UIKit_Sim/UIKit-3318.16.14/Keyboard/UIKeyboardTaskQueue.m:374 2014-11-15 17:41:29.540 Wavesss[8462:846477] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'

尽管我很难找到解决方案,但请帮助我, 似乎我无法在 View Controller 之间传递,而 url 任务仍在其他线程上执行。 提前谢谢大家!

最佳答案

您的 checkLogin 函数正在另一个线程上被调用,因此您需要切换回主线程才能调用 self.performSegueWithIdentifier。我更喜欢使用 NSOperationQueue:

func checkLogin(succeed: Bool, msg: String) {
    if (succeed) {
        NSOperationQueue.mainQueue().addOperationWithBlock {
            self.performSegueWithIdentifier("logInTrue", sender: self)
        }        
    }
}

替代:xCode 10.1 1/2019

func checkLogin(succeed: Bool, msg: String) {
    if (succeed) {
        OperationQueue.main.addOperation {
            self.performSegue(withIdentifier: "logInTrue", sender: self)
           }        
      }
 }

https://stackoverflow.com/questions/26947608/

相关文章:

json - 如何强制将请求正文解析为纯文本而不是 Express 中的 json?

php - 如何防止 json_encode() 删除包含无效字符的字符串

json - 在单行上从 jq 获取输出

json - angularjs - ng-重复 : access key and value fr

c# - 使用 C# 调用 json

javascript - Javascript对象和JSON对象有什么区别

java - 使用 GSON 解析 JSON 文件

javascript - 未捕获的类型错误 : Cannot read property 'owne

json - 雅虎财经全币种报价 API 文档

PHP json_encode - JSON_FORCE_OBJECT 混合对象和数组输出