How to cancel asynchronous NSURLConnection

Canceling the calling instance method in NSURLConnection most often does not cancel the connection at all.

I am performing an asynchronous NSURLConnection in NSOperation. If the operation is canceled, the connection is terminated, causing the cancellation in the NSURLConnection, and then establishing the connection to zero.

Is there a way to cancel the connection immediately? Most often, it continues to run in the background until the request is complete, even if the connection is canceled and set to zero. The NSOperation subclass is freed after the connection is canceled when the connection is dropped. Even after that, the asynchronous connection continues to work!

Is there any other way to undo it? Or is it possible to cancel its stream?

Here is the code snippet from the main method of the NSOperation subclass:

// Create and start asynchronous connection self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; [request release]; while(!isFinished) { if(self.isCancelled) { [self.connection cancel]; self.connection = nil; [self uploadCanceledDelegate]; return; } // Special sleep because callbacks are executed on same thread as this loop [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } 

NOTE. . This behavior only occurs when WiFi is turned on. It works great with 3G / Edge / GPRS

+4
source share
3 answers

This may be a problem with the Apple documentation.

It is possible that the connection is currently waiting on a blocked thread, and the OS will not do anything immediately while the thread is blocked. The thread will not be canceled until it is unlocked at some later point in time. Therefore, you should not release any objects that process these canceled connections until an unknown point appears in the future, when a socket that is waiting for a timeout or is closed.

If you experience leaks or malfunctions, you can try moving the "canceled" operation objects to another queue of things waiting to exit in a few seconds, or perhaps even in a few minutes.

+6
source

I had the same problem when using lazy image loading (loading an asynchronous image), what I did was all my NSURLRequests in the NSMUtable array, and when I needed to undo all this, I did it through a for loop.

0
source

This may be due to the fact that cancel is a message, and the message manager cannot send a message while the current function is in the while loop. I hope that my understanding of Objective-C messages is correct here, but it might work if you allow the functions to complete and process another cleanup code in a callback that fires when the isFinished flag is set. I am ready to make mistakes, but I think the problem may be a while loop.

-3
source

All Articles