【问题标题】:imageWithContentsOfFile return nil And imageWithData return nilimageWithContentsOfFile 返回 nil 和 imageWithData 返回 nil
【发布时间】:2016-09-06 04:14:18
【问题描述】:

我想从路径中使用 imageWithContentsOfFile 获取图像,但它返回 nil。然后我尝试 imageWithData,它返回 nil,但数据不是 nil。请帮帮我,非常感谢! 像“/var/mobile/Containers/Data/Application/F865E931-B673-4295-8AC3-B5C3560A10D6/Library/Caches/pic/0513041abff0edbb0e909a1364abe2ed.jpg”这样的路径 对了,模拟器上不会出现这种情况,只有真机上才返回nil case。

NSString * strDestinationPath = [[mainKeepData getPicturesPath] stringByAppendingString:imageName];
NSFileManager * fileManager = [NSFileManager defaultManager];
        BOOL bl1 = [fileManager fileExistsAtPath:strDestinationPath];
        if (bl1 == NO)
        {
            [request setDownloadDestinationPath:strDestinationPath];
            [request setCompletionBlock:^(void){
                UIImage * image=[UIImage imageWithContentsOfFile:strDestinationPath];
                [PictureDict setValue:image forKey:strGUID];
                [self.delegate DownloadPictureIsOver:YES RequestID:RequetID];
            }];

            [request setUserInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",strGUID] forKey:@"name"]];
            [networkQueue addOperation:request];
        }
        else
        {
            NSData *imageData = [NSData dataWithContentsOfFile:strDestinationPath];
           UIImage *image = [UIImage imageWithData:imageData];
            [PictureDict setValue:image forKey:strGUID];
        }

获取路径函数

+(NSString *)getPicturesPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];

    NSString *filePath = [cachesDir stringByAppendingPathComponent:@"/pic/"];
    filePath=[filePath stringByAppendingString:@"/"];
    return filePath;
}

【问题讨论】:

  • 如何获取 strDestinationPath ?
  • 你检查过,路径引用的数据是否是合法的jpeg?
  • 路径和图片可用
  • 只有少数案例返回 nil 不是全部
  • 我可以在上面的代码中知道您的要求是什么吗?根据您的代码,我认为您正在从服务器下载多个图像并存储在本地缓存中吗?

标签: ios objective-c uiimage


【解决方案1】:

可以试试这个,可能对你有帮助

NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/pic/"];

return stringPath;

// If you want particular image path
stringPath  = [stringPath stringByAppendingPathComponent:@"Your Img Name"];
UIImage *image = [UIImage imageWithContentsOfFile:stringPath];

编码愉快...

【讨论】:

  • sailendra kumar,谢谢。但图像仍然为零
  • sailendra kumar 是的
  • 我使用了 imageWithContentsOfFile/imageWithData,大多数时候返回的图像不是零。但是几张图的回报是零。
  • 好的..不是每次都复制。返回 nil 的图像,只需验证它是否在文档目录中(在您的图片中)
  • 我相信它存在。 dataWithContentsOfFile 返回数据不为零。如果我使用模拟器,图像(相同的图像)将显示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 2019-06-20
  • 2017-12-16
  • 2014-09-27
相关资源
最近更新 更多