Creating and Undoing NSURLConnection

I have an NSURLConnection that works fine when I allow the download to complete. But if the user clicks the back button, that is, the webview will disappear, I want to cancel the NSURLConnection. But if you have a webview call to this class when viewWillDissapear is called, then I do:

[conn cancel] 

I get an NSINValidArgument exception.

A connection is defined as instance data in a .h file as:

 NSURLConnection *conn; 

This is where async is triggered:

 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:articleURL]]; if ([NSURLConnection canHandleRequest:request] && reachable) { // Set up an asynchronous load request conn = [NSURLConnection connectionWithRequest:request delegate:self]; loadCancelled = NO; if (conn) { NSLog(@" ARTICLE is REACHABLE!!!!"); self.articleData = [NSMutableData data]; } } 
+4
source share
1 answer

The reason you got the exception is because you are saving the autorelease object in the instance variable.
"conn" will be automatically released immediately after pressing the user button. After that you call cancellation. Therefore, you have an exception.
To prevent this, you must save the NSURLConnection object if you save it in an instance variable.

 conn = [[NSURLConnection connectionWithRequest:request delegate:self] retain]; 

or

 conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

Remember to release this in the dealloc method.

+11
source

Source: https://habr.com/ru/post/1299224/


All Articles