2013-10-07 63 views
0

我有這樣的代碼:撤銷文件下載

- (void)downloadFile:(void (^)(BOOL success))callback { 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
      NSURL *url = [NSURL URLWithString:@"http://stackoverflow.com/largefile.bin"]; 
      NSData *data = [NSData dataWithContentsOfURL:url]; 
      callback(YES); 
    }); 
} 

而且我有一個創建並調用此方法前所示,然後回調後將會被隱藏進度對話框。我需要以某種方式能夠取消文件下載。我怎樣才能做到這一點?

+2

您需要使用NSURLConnection的和NSURLConnectionDelegate。創建一個班級來完成你所有的下載。 – Fogmeister

+0

你是對的,謝謝! – mixel

回答

0

解答基於@Fogmeister評論。

Downloader.h

@interface Downloader : NSObject<NSURLConnectionDataDelegate> 

- (void) download:(NSURL *)url; 
- (void) cancel; 

@end 

Downloader.m

@implementation Downloader { 
    NSMutableData * receivedData; 
    NSURLConnection * urlConnection; 
} 

- (void) download:(NSURL *)url 
{ 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; 
    receivedData = [[NSMutableData alloc] initWithLength:0]; 

    urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
} 

- (void) cancel 
{ 
    if (urlConnection != nil) { 
     [urlConnection cancel]; 
     urlConnection = nil; 
    } 
} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    urlConnection = nil; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [receivedData appendData:data]; 
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    urlConnection = nil; 
    // process receivedData 
}