iosobjective-cnsurlconnectionnsconnection

NSURLConnection cancellation callback


Is it possible to catch NSURLConnection cancel using a callback?

If I'm using this code

-(void) pleaseStopDownload {
cancelled = YES;
    [conn cancel];
    conn = nil;
    [self myUpdateUImessage];
}

from time to myUpdateUImessage is called before this callback

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"didReceiveData");
if (!cancelled) {
//this code inside brackets suddenly is calling:(
//not always but from time to time
    summ += data.length;
    if (_progressHandler != nil)
        _progressHandler(data, summ, max);
} else {
return;
}
}

So the User interface is not updated properly! That is, the final UI is shown than progress UI.

EDIT the problem was about

NSOperationQueue *tempQueue = [[NSOperationQueue alloc] init];
[conn setDelegateQueue:tempQueue];

correct NSQueue is NSOperationQueue *tempQueue = [NSOperationQueue mainQueue];


Solution

  • Is it possible to catch NSURLConnection cancel using a callback?

    No.

    From the official documentation here:

    After this method is called, the connection makes no further delegate method calls.

    This means you should handle the UI cleanup as soon as you call cancel and not rely on the _cancelled variable because - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data is not expected to be invoked anymore.

    What I advice, is to call a cleanup method from your cancellation code:

    -(void) pleaseStopDownload {
        [conn cancel];
        conn = nil;
        [self handleCancelledDownload];
    }