Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and canceling an NSURLConnection

I have a NSURLConnection that is working fine when I allow the load to complete. But if the user hits the back button, meaning the webview will dissappear, I want to cancel the NSURLConnection in progress. But if have the webview call into this class when viewWillDissapear is called, and then I do:

[conn cancel]

I get an NSINValidArgument exception.

The connection is defined as instance data in the .h file as:

NSURLConnection *conn;

The async is initiated here:

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];
        }
    }
like image 870
Don Wilson Avatar asked Dec 22 '22 06:12

Don Wilson


1 Answers

The reason why you got the exception would be you are saving an autorelease object to an instance variable.
"conn" would be auto-released immediately when a user click back button. After that, you call cancel. Therefore, you had the exception.
To prevent this, you should retain NSURLConnection object when you keep it in an instance variable.

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

or

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

Don't forget to release this in the dealloc method.

like image 119
tomute Avatar answered Jan 09 '23 13:01

tomute