0

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

如果我使用此代码

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

myUpdateUImessage在此回调之前调用from time to

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

正确NSQueue的是 NSOperationQueue *tempQueue = [NSOperationQueue mainQueue];

4

1 回答 1

2

是否可以使用回调捕获 NSURLConnection 取消?

不。

这里的官方文档:

调用此方法后,连接不再进行委托方法调用。

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

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

-(void) pleaseStopDownload {
    [conn cancel];
    conn = nil;
    [self handleCancelledDownload];
}
于 2016-04-25T15:16:54.427 回答