本文介绍了在URLSession.shared.dataTask之后调用performSegue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用URLSession.shared.dataTask发送发布请求后执行Segue
I want to performe a Segue after sending a post request using URLSession.shared.dataTask
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)
}
}
}
登录:
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 :
有更好的方法吗?
推荐答案
尝试这种方式:
if response.range(of: "failure") == nil {
NSOperationQueue.mainQueue().addOperationWithBlock {
self.performSegue(withIdentifier: "home", sender: nil)
}
}
swift3:
if response.range(of: "failure") == nil {
OperationQueue.main.addOperation {
self.performSegue(withIdentifier: "home", sender: nil)
}
}
这篇关于在URLSession.shared.dataTask之后调用performSegue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!