2015-10-28 39 views
0

我有一个tableview,其中从网上下载照片。为了这个目的,使用类别异步下载远程照片。在下载过程中,显示​​本地图像,直到下载完成后,来自Web的图像替换占位符。所有这些工作正常。我的问题是我需要确定新图像何时被加载以便在本地保存。IOS/Objective-C:确定异步下载何时完成,然后再保存数据

这是自定义tableview单元格中的代码,用于显示并尝试保存图像。问题在于它有时会保存占位符,而其他时间会根据下载速度保存Web图像。

NSString *picURL = [NSString stringWithFormat:@"http://www.~.com/pics/%@",item.pic]; 
NSString *picname = item.pic; 
[self.iconView setImageWithRemoteFileURL:picURL placeHolderImage:[UIImage imageNamed:@"item.jpg"]]; //this method is in a category 
//Only want to do following after the asynchronous download is finished... 
[self saveImage:self.iconView asPic:picname]; 

下面是类别中的一些代码,但是我一直无法让委托模式工作。想知道是否有其他方法。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    //done downloading data - process completed! 
    [self.delegate didCompleteDownloadForURL:self.url withData:self.data]; 

} 

#pragma mark DownloadHelperDelegate 

-(void)didCompleteDownloadForURL:(NSString *)url withData:(NSMutableData *)data 
{ 
    //handles the downloaded image data, turns it into an image instance and saves then it into the ImageCache singleton. 

    UIImage *image = [UIImage imageWithData:data]; 

    if (image == nil) {//something didn't work out - data may be corrupted or a bad url 
     return; 
    } 

    //cache the image 
    ImageCache *imageCache = [UIImageView imageCache]; 
    [imageCache storeCachedImage:image forURL:url]; 

    //update the placeholder image display of this UIImageView 
    self.image = image; 


//At this point I have the image but how do I start save. 
I could put the save code right here but this is a category that 
gets reused in multiple places and the save code would vary 
depending on where it is used. 
     } 

在此先感谢您的任何建议。

+1

? – bbum

+0

你是什么意思“设置”代表?一个协议是在类别中指定的,但它是一个时髦的类别(我在其他地方)有隐藏的方法。该类别包含在tableview单元格中。我试图让单元订阅协议,但得到警告说协议没有定义。在任何情况下,协议方法都不会在单元格中触发。我问了一个关于让代表工作的单独问题,但没有得到答案。这个问题正在寻找代表方法的替代方案。 – user1904273

+0

某处需要设置委托,以使'self.delegate'返回非'nil'的内容。 – bbum

回答

1

我建议你使用NSURLSession或在您下载helper类类似的东西:你在哪里设置委托

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
NSURLSessionTask *task = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.lombax.it/ok.gif"]] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { 
    // here, the file download has finished and you can copy it and assign to the icon file 
    NSLog(@"File location is: %@", location); 
}]; 
[task resume]; 
相关问题