下载的图像在文档目录中为零字节



我正在尝试从webburl下载和存储图像到文档目录。
这是我的代码。

-(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);
    }
}


每次"头像照片存储在:…"将在控制台打印。但如果我去那个路径,检查图像,它的大小是0字节,没有任何预览。
webburl的图像是正确的,我也可以从web浏览器检查。我不知道代码哪里出错了。
你能帮我解决这个问题吗?

dataWithContentsOfURL没有从服务器下载图像asynchronously。现在,如果imagesize足够大,那么下载需要一些时间。你直接尝试将图像存储到文档目录。我认为这会产生问题。您应该使用NSUrlSession获取图像,您应该从NSUrlSession方法调用的完成处理程序将数据写入本地存储,如文档目录。你也可以使用AFNetworking来管理这类东西。

第二件事使用

 [data writeToFile:path atomically:NO];

将数据存储到文档目录,路径是最终路径,对于不同的数据应该是唯一的。

[NSData dataWithContentsOfURL]不是异步方法

如果你调试你的代码,你会发现imagedata将是nil

你应该先获取imagedata然后存储它

您可以使用AFNetworing, SDWebImage框架或直接使用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]; } }];

good day:)

最新更新