[英]After URLSession.shared.dataTask its either not returning error or success
[英]Call performSegue after URLSession.shared.dataTask
我想使用URLSession.shared.dataTask發送發布請求后執行Segue
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()
}
}
有時會因以下錯誤而崩潰:
由於未捕獲的異常'NSInternalInconsistencyException'而終止應用程序,原因:'-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished]只能從主線程調用。
有更好的方法嗎?
嘗試這種方式:
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)
}
}
如錯誤所示,您需要像這樣在Main Thread中調用執行segue
DispatchQueue.main.async {
self.performSegue(withIdentifier: "home", sender: nil)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.