简体   繁体   中英

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.

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 . NSURLSessionTask s have a cancel() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM