ios - 停止从服务器加载 NSData

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

}

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

谢谢!

最佳答案

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

您设置了一个 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/

相关文章:

ios - 如何将字符串日期转换为 NSDate?

swift - 如何根据日期进行过滤,以便每周只有一个元素?

ios - Swift 委托(delegate)传递信息

ios - 在不滚动整个 NC 的情况下在 iOS Today Extension 中绘制

ios - swift 3 获取共享数据的用户信息

objective-c - GCDAsyncUdpSocket 无法针对 iOS 进行编译

objective-c 运行时错误 "Use of undeclared identifier ' objc_property_t'”

ios - UITextField 未成为 Collection View 中的第一响应者

swift - 如何在 Swift 中检查有效的 Date()

ios - swift UITableView : Datasource assigning Issue