可取消的文件下载

时间:2013-10-07 06:42:37

标签: ios objective-c download

我有这样的代码:

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

此外,我在调用此方法之前创建并显示了进度对话框,然后在回调后隐藏。我需要以某种方式取消文件下载。我怎么能这样做?

1 个答案:

答案 0 :(得分: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
}