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

我也有在调用此方法之前创建并显示的进度对话框,然后在回调后将被隐藏。我需要以某种方式能够取消文件下载。我怎样才能做到这一点?

4

1 回答 1

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
}
于 2013-12-21T11:13:26.870 回答