停止从服务器加载NSData

时间:2013-08-14 22:56:43

标签: ios objective-c nsdate

我有以下方法,它基本上将一组图像数据加载到一个数组中:

-(void)loadImages:(NSMutableArray*)imagesURLS{
    //_indexOfLastImageLoaded = 0;
    [_loadedImages removeAllObjects];
    _loadedImages = [[NSMutableArray alloc]init];;
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        for (int i=0; i<imagesURLS.count;i++){
            NSLog(@"loading image for main image holder at index %i",i);
            NSData *imgData = [NSData dataWithContentsOfURL:[imagesURLS objectAtIndex:i]];
            UIImage *img = [UIImage imageWithData:imgData];
            [_loadedImages addObject:img];
            //_indexOfLastImageLoaded++;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"_loadedImages download COMPLETE");                      
        });
    });

}

我希望能够阻止它,例如,当用户离开视图控制器时正在加载这些图像。这样做的最佳方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:4)

您无法取消NSData dataWithContentsOfUrl:。实现可取消的异步下载的最佳方法是使用NSURLConnectionNSURLConnectionDataDelegate

您设置了一个NSMutableData对象,以便以块的形式存储所有数据。然后,当所有数据到达时,您将创建图像并使用它。

·H

@interface ImageDownloader : NSObject <NSURLConnectionDataDelegate>
@property (strong, nonatomic) NSURLConnection *theConnection;
@property (strong, nonatomic) NSMutableData *buffer;
@end

的.m

-(void)startDownload
{
    NSURL *imageURL = [NSURL URLWithString: @"http://example.com/largeImage.jpg"];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL: imageURL];
    _theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate: self startImmediately: YES];
}

-(void)cancelDownload
{
    // CANCELS DOWNLOAD
    // THROW AWAY DATA
    [self.theConnection cancel];
    self.buffer = nil;
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // INITIALIZE THE DOWNLOAD BUFFER
    _buffer = [NSMutableData data];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // APPEND DATA TO BUFFER
    [self.buffer appendData: data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     // DONE DOWNLOADING
    // CREATE IMAGE WITH DATA
    UIImage *theImage = [UIImage imageWithData: self.buffer];
}

答案 1 :(得分:2)

如果您希望更加灵活地使用取消请求,我建议您使用NSOperationQueue而不是连续推送所有请求。

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    for (int i=0; i<allImagesCount; i++) {
        [queue addOperationWithBlock:^{
            // load image
        }];
    }

    // for canceling operations
    [queue cancelAllOperations];

在您当前的代码中,您还可以定义静态字段并检入for循环,但最好的方法是使用SDWebImage - https://github.com/rs/SDWebImage来加载图像异步。