2016-09-07 68 views
0

我試圖從webURL下載圖像並將其存儲到文檔目錄。
這是我的代碼。下載的圖像在文檔目錄中有零字節

-(void)downloadPersonPhoto:(NSDictionary *)dict 
{ 
    NSString *imageUrlStr=[dict objectForKey:@"personPhoto"]; 
    if ([[dict valueForKey:@"personAvatarStore"] isEqualToString:@"AMAZON"]) 
    { 
     imageUrlStr = [imageUrlStr stringByReplacingOccurrencesOfString:@"original" withString:@"100x100"]; 
    } 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSString *documentsDirectory = [self getDocumentDirectory]; 
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"personPhoto"]; 
    if (![fileManager fileExistsAtPath:dataPath]) { 
     [fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder 
    } 
    NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[dict valueForKey:@"personId"]]]; 
    if (![fileManager fileExistsAtPath:fullPath]) { 
     NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]; 
     [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; 
     NSLog(@"Avatar Photo stored at: %@", fullPath); 
    } 
} 


每次「存儲在...的頭像照片」都將在控制檯中打印。但是,如果我去那條路徑並檢查圖像,那麼它有零字節的大小,並沒有任何預覽可用。
webURL的圖像是正確的我也可以從網頁瀏覽器檢查。 我不知道我的代碼在哪裏出錯。
你能幫我解決嗎?
在此先感謝。

回答

1

dataWithContentsOfURL未從服務器下載圖片asynchronously。現在如果圖像大小足夠大,下載需要一些時間。並且您直接嘗試將圖像存儲到文檔目錄。我認爲這會造成問題。您應該使用NSUrlSession獲取圖像,並且您應該將數據寫入本地存儲器,如NSUrlSession方法調用完成處理程序的文檔目錄。你也可以使用AFNetworking來管理這種類型的東西。

第二件事使用

[data writeToFile:path atomically:NO]; 

來存儲數據到文件目錄和路徑是最後路徑應該是不同的數據是唯一的。

1

[NSData dataWithContentsOfURL]不是異步方法

如果調試你的代碼,你會發現imagedata將是零

你應該先把圖象 - 然後存儲它

可以使用AFNetworingSDWebImage框架或只是使用NSURLSession下載它

這裏是我自己的一個解決方案

[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError * error) { //error if (error) { //handle error return; } if (data) { //store imagedata [data writeToFile:filepath atomically:NO]; } }];

好日子:)