iBrad Apps iBrad Apps - 1 year ago 85
iOS Question

Properly cancel NSURLConnection?

I am creating my NSURLConnection like so:

theConnection = [[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self];

I have looked in the NSURLConnection documentation and apparently the cancel API works for async requests, so will that work in the scenario?

Anyway, in my other class while the NSURLConnection is in progress I try to do this:

[mgr.theConnection cancel];
[mgr.theConnection release];

However, the delegate still gets called which I do not want. So how do I properly make sure I cancel the connection so that its delegate calls are canceled as well?


2012-08-17 23:01:11.820 app[14097:707] Will cancel connection=(null)
2012-08-17 23:01:11.821 app[14097:707] Did cancel connection
2012-08-17 23:01:11.821 app[14097:707] Did release connection
2012-08-17 23:01:20.330 app[14097:707] didReceiveResponse
2012-08-17 23:01:20.331 app[14097:707] didReceiveData
2012-08-17 23:01:20.332 app[14097:707] connectionDidFinishLoading

Answer Source

Obviously something is happening that is not clear. What I would suggest is adding some log messages to verify that in fact the timing is as you think:

// Add a simple log like (NSLog(@"%@", @"conn_del"); to all your delegate methods)

Then addend you cancelation code with this:
NSLog(@"Will cancel connection=%@", mgr.theConnection);
[mgr.theConnection cancel];
NSLog(@"Did cancel connection");
// [mgr.theConnection release]; assuming a retained property, this is not the way to do it
mgr.theConnection = nil; // this is the proper way - release and nil out the property
NSLog(@"Did release connection");

I've had cancel in my code and its been tested for several years, no problems. I suspect you may learn something from the test above. I would be shocked to hear you get any messages after you see "Did cancel connection" on the console, but you might between the "Will" log and it.

EDIT: per your test, either mgr or mgr's theConnection property, is nil. This is the root cause of your problem. When you figure out why its nil and fix it, the connection will cancel and the same NSLogs will show no more delegate messages afterwards.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download