简体   繁体   English

在URLSession.shared.dataTask之后调用performSegue

[英]Call performSegue after URLSession.shared.dataTask

I want to performe a Segue after sending a post request using URLSession.shared.dataTask 我想使用URLSession.shared.dataTask发送发布请求后执行Segue

ViewController: ViewController:

    @IBAction func Connection(_ sender: AnyObject) {
    let loginFunc = Login()
    loginFunc.login(username: username.text!, password: password.text!) { jsonString in
        let response = jsonString
        print(response)
        if response.range(of: "failure") == nil {
            self.performSegue(withIdentifier: "home", sender: nil)
        }
    }
}

Login: 登录:

class Login {
// the completion closure signature is (String) -> ()
func login(username: String, password: String, completion: @escaping (String) -> ()) {
    var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/login_check")!)
    request.httpMethod = "POST"
    let postString = "_username=" + username + "&_password=" + password
    request.httpBody = postString.data(using: .utf8)
    var responseString = ""
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

            responseString = String(data: data, encoding: .utf8)!
            completion(responseString)
        }
        task.resume()
    }
}

It sometimes crash with the following error : 有时会因以下错误而崩溃:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.' 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'-[UIKeyboardTaskQueue waitUntilAllTask​​sAreFinished]只能从主线程调用。

Is there a better way to do it ? 有更好的方法吗?

Trying this way : 尝试这种方式:

 if response.range(of: "failure") == nil {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                 self.performSegue(withIdentifier: "home", sender: nil)
            }
        }

swift3: swift3:

if response.range(of: "failure") == nil {
           OperationQueue.main.addOperation {
                self.performSegue(withIdentifier: "home", sender: nil)
            }
}

As the error says you need to call perform segue in Main Thread like this 如错误所示,您需要像这样在Main Thread中调用执行segue

DispatchQueue.main.async {
    self.performSegue(withIdentifier: "home", sender: nil)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 URLSession.shared.dataTask 之后要么不返回错误要么成功 - After URLSession.shared.dataTask its either not returning error or success URLSession.shared.dataTask 冻结 UI - URLSession.shared.dataTask freezes the UI 在URLSession.shared.dataTask中执行performSegueWithIdentifier(with:url) - performSegueWithIdentifier while in URLSession.shared.dataTask(with: url) 为什么没有在第二个 URLSession.shared.dataTask 之后/内执行代码,即在初始 URLSession.shared.dataTask 的 do 块内? 迅速 - Why isn't code being executed after/within a second URLSession.shared.dataTask, that is within an initial URLSession.shared.dataTask’s do block? Swift 当应用程序处于后台时调用URLSession.shared.dataTask - Invoke URLSession.shared.dataTask when the app is background 在URLSession.shared.dataTask期间从异步关闭存储数据 - Storing data from an asynchronous closure during URLSession.shared.dataTask URLSession.shared.dataTask的完成处理程序内部的闭包 - closure inside completion handler of URLSession.shared.dataTask 使用URLSession.shared.dataTask中的JSON和字典进行Swift 3编译器错误 - Swift 3 Compiler Errors with JSON and Dictionaries within URLSession.shared.dataTask 使用 URLSession.shared.dataTask 发出 api 请求 - Making an api request using URLSession.shared.dataTask 获取URL响应状态代码URLSession.shared.dataTask - Get http response status code of URLSession.shared.dataTask
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM