1

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

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

}

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

谢谢!

4

2 回答 2

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];
}
于 2013-08-14T23:05:20.673 回答
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加载图像异步。

于 2013-08-14T23:12:45.643 回答