停止urlRequest onViewDisappear

时间:2019-02-19 14:50:27

标签: swift

我按如下方式从服务器加载json信息,但是当我单击鼠标太快转到另一个页面时,请求将继续在后台尝试,并且警告说viewController不再存在。如何取消onViewDisappear上的所有请求?

if let requestURL = URL(string: "https://www.example.com/file.php") {

        var urlRequest = URLRequest(url: requestURL)
        urlRequest.httpMethod = "POST"
        let postString = "email=\(loginUsername.text!)"
        urlRequest.httpBody = postString.data(using: .utf8)

        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest as URLRequest) {  (data, response, error) in

            if let data = data {
                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {

                        // Async Stuff
                        DispatchQueue.main.async{

                            // do things
                        }

                        DispatchQueue.main.async(execute: {
                        })
                    }
                } catch {
                    print("Error: \(error)")
                }
            }
        }
        task.resume()
    }

3 个答案:

答案 0 :(得分:1)

将您的请求保存在某个地方,然后远离控制器调用:

task.cancel()

答案 1 :(得分:0)

您可以使用2种方式

  1. 使用task.cancel()

  2. 使用task.suspend()

    task.cancel()在做Cancels the task.

    task.suspend()在做Temporarily suspends a task.

答案 2 :(得分:0)

class DataCall {
    var task: URLSessionDataTask?

    func load() {
        guard let requestURL = URL(string: "https://www.example.com/file.php") else { return }

        var urlRequest = URLRequest(url: requestURL)
        urlRequest.httpMethod = "POST"
        let postString = "email=\(loginUsername.text!)"
        urlRequest.httpBody = postString.data(using: .utf8)

        let session = URLSession.shared
        task = session.dataTask(with: urlRequest as URLRequest) {  (data, response, error) in

            if let data = data {
                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {

                        // Async Stuff
                        DispatchQueue.main.async{

                            // do things
                        }
                    }
                } catch {
                    print("Error: \(error)")
                }
            }
        }
        task.resume()
    }

    func stopTask() {
        task.cancel()
    }
}

然后在您的viewWillDissapear中致电dataCall.stopTask()