【问题标题】:Call performSegue after URLSession.shared.dataTask在 URLSession.shared.dataTask 之后调用 performSegue
【发布时间】:2016-11-09 14:19:56
【问题描述】:

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

视图控制器:

    @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 waitUntilAllTask​​sAreFinished] 只能从主线程调用。”

有没有更好的方法?

【问题讨论】:

  • 尝试将您的performSegue 分派回主队列。

标签: ios swift nsurlsessiondatatask


【解决方案1】:

试试这个方法:

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

【讨论】:

  • 效果很好!如果我理解得很好 OperationQueue 在执行 Sergue 之前正在等待请求完成?
  • 是的!操作保留在该队列中,直到它被显式取消或完成其任务的执行
  • 喜欢你的回答。谢谢。
【解决方案2】:

正如错误所说,您需要像这样在主线程中调用 perform segue

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多