简体   繁体   中英

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];

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM