gpt4 book ai didi

ios - 在 URLSession.shared.dataTask 之后调用 performSegue

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:47 24 4
gpt4 key购买 nike

我想在使用 URLSession.shared.dataTask 发送发布请求后执行 Segue

View Controller :

    @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()
}
}

它有时会因以下错误而崩溃:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'

有更好的方法吗?

最佳答案

尝试这种方式:

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

swift 3:

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

关于ios - 在 URLSession.shared.dataTask 之后调用 performSegue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40509159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com