2015-10-28 38 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]; 
相關問題