Martin Vidic
Martin Vidic

Reputation: 813

stop urlRequest onViewDisappear

I load my json info from my server as follows, but when I click away to a different page too soon, the request keeps trying in the background and there is a warning that the viewController can't be found anymore. How would I cancel all requests 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()
    }

Upvotes: 0

Views: 122

Answers (2)

Alex Ioja-Yang
Alex Ioja-Yang

Reputation: 1533

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

Then in your viewWillDissapear you call dataCall.stopTask().

Upvotes: 0

pckill
pckill

Reputation: 3759

Save your requests somewhere and then on moving away from the controller call:

task.cancel()

Upvotes: 1

Related Questions