Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel on-going HTTP request in Swift?

My code does GET request like this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
    // ...

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        if error != nil {
            println("error = \(error)")
            return
        }

        if let HTTPresponse = response as? NSHTTPURLResponse {
            if HTTPresponse.statusCode == 200 { // Successfully got response
                var err: NSError?
                if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &err) as? [String : AnyObject] {
                    // Success decoding JSON
                } else {
                    // Failed -> stop activity indicator
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.activityIndicator.stopAnimating()
                    })
                }
            }
            task.resume()
        })
    }
}

If viewWillDisappear() gets called before the request finishes, I want to stop the request.

Right now, it seems like the view doesn't disappear before the request finishes. Is there a way to cancel the ongoing GET/POST request?

like image 341
Joon. P Avatar asked Jul 10 '15 15:07

Joon. P


People also ask

How do I cancel HTTP request?

We can use the AbortController object and the associated AbortSignal with the Fetch API to make cancelable HTTP requests. Once the AbortSignal is sent, the HTTP request is canceled and won't be sent if the cancellation signal is sent before the HTTP request is done.

How do I cancel a swift request?

You can explicitly cancel a task by calling its cancel() method. Any task can check Task.

How do I stop URLSession?

Instead, just create your single URLSession() and let URLSession create its own OperationQueue instead of accidentally using whatever queue you may be on. Once you do this, early cancellation of the request is as simple as task. cancel() , which will return a URLError.


1 Answers

Yes, but you have to store it for outside access - the task has a method cancel() which you can use, just like you're using resume().

For viewDidDisappear() I'd recommend having it as object property - var currentTask: NSURLSessionTask?, in your dispatch you would have self.currentTask = ... instead of let task = ... and in your viewDidDisappear() you would call self.currentTask?.cancel().

like image 71
Michal Avatar answered Sep 20 '22 23:09

Michal