NSURLConnection取消回调

时间:2016-04-25 15:00:28

标签: ios objective-c nsurlconnection nsconnection

是否可以使用回调来捕获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];

1 个答案:

答案 0 :(得分:2)

  

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

没有

来自官方文档here

  

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

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

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

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