NSURLConnection 取消回调

NSURLConnection cancellation callback

是否可以使用回调捕获 NSURLConnection cancel

如果我使用此代码

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

从时间到 myUpdateUImessage 在此回调之前调用

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

所以用户界面没有正确更新!也就是说,最后的 UI 显示的比进度 UI.

编辑 问题是关于

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

正确的NSQueueNSOperationQueue *tempQueue = [NSOperationQueue mainQueue];

Is it possible to catch NSURLConnection cancel using a callback?

没有

来自官方文档here:

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

这意味着您应该在调用 cancel 后立即处理 UI 清理,而不是依赖 _cancelled 变量,因为预计不会调用 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data没有了。

我的建议是从您的取消代码中调用清除方法

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