2016-09-07 67 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]; } }];

好日子:)