2016-04-25 81 views
0

是否有可能使用回調趕上NSURLConnection cancelNSURLConnection取消回調

如果我使用此代碼

-(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。

編輯 的問題是關於

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

正確NSQueueNSOperationQueue *tempQueue = [NSOperationQueue mainQueue];

回答

2

是否有可能趕上NSURLConnection的使用取消回調?

從官方文檔here:這種方法被稱爲

後,連接不再有進一步的委託方法調用。

這意味着你應該儘快處理UI清理您撥打cancel因爲- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data預計不會再被調用不能依靠_cancelled變量。

我的意見,是從你的取消代碼調用清理方法

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