Robert Constantinescu
Robert Constantinescu

Reputation: 349

iOS Swift - NSURLConnection.sendAsynchronousRequest cancel request

I'm trying to cancel an asynchronous request if there is a problem with the internet connection.

var connection: NSURLConnection!
self.connection = NSURLConnection.sendAsynchronousRequest(request2, queue: NSOperationQueue.mainQueue())
{

    (response, data, error) in ();
    if(response != nil){
    if let Data: AnyObject! ..... }

This is the code. I'm trying to cancel the request by:

self.connection.cancel()

but I have some errors : Cannot assing a value of type 'void' to a value of type NSURLConnection.

Upvotes: 1

Views: 980

Answers (1)

MLQ
MLQ

Reputation: 13511

sendAsynchronousRequest is a function that returns nothing, and yet you're assigning it to self.connection.

You don't need an NSURLConnection instance to send an asynchronous request--it is a class function, you pass it your NSURLRequest, and a custom NSOperationQueue or a completionHandler, optionally.

Also, you can't really cancel a request made through sendSynchronous- or sendAsynchronousRequest. You will need to make an NSURLSessionTask, to be used in combination with NSURLSession. NSURLSessionTasks have a cancel() method.

Upvotes: 1

Related Questions