我有以下方法,它基本上将图像数据数组加载到数组中:
-(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");
});
});
}
例如,当用户离开正在加载这些图像的 View Controller 时,我希望能够停止它。最好的方法是什么?
谢谢!
最佳答案
您无法取消 NSData dataWithContentsOfUrl:
.实现可取消的异步下载的最佳方法是使用 NSURLConnection
和 NSURLConnectionDataDelegate
.
您设置了一个 NSMutableData 对象来累积所有数据,因为它以 block 的形式出现。然后,当所有数据都到达时,您创建图像并使用它。
。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];
}
关于ios - 停止从服务器加载 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243703/