无法使用[UIImage imageWithContentsOfFile:]创建UIImage,文件就在那里

see*_*nte 2 file uiimage ios

我有谷歌这个问题,大多数使用错误的方法:[UIImage imageNamed:].我不是.我确定该文件已存在.以下代码在iOS8.1上运行.

        self.cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        UIImage *avatorImage = [[UIImage alloc] initWithCGImage:headCGImage];
        NSString *avatorName = [[[NSUUID alloc] init] UUIDString];
        avatorName = [avatorName stringByAppendingPathExtension:@"png"];
        avatorName = [self.cachePath stringByAppendingPathComponent:avatorName];
        NSData *avatorImageData = UIImagePNGRepresentation(avatorImage);
        BOOL writeSuccess = [avatorImageData writeToFile:avatorName atomically:YES];
        if (!writeSuccess)
           NSLog(@"Write to File Error");
        //read file form other place, it's just nil.
        UIImage *imageFromFile = [UIImage imageWithContentsOfFile:pathForImage];
Run Code Online (Sandbox Code Playgroud)

然后我用[UIImage imageWithContentsOfFile:]来获取UIImage.有一件奇怪的事情.当我第一次运行app时,一切正常.但我停止应用程序,并再次运行它,[UIImage imageWithContentsOfFile:]只返回一个零.我不知道为什么.

---------------------------我是一个可爱的线------------------ ---------

Summery:从iOS8开始,NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)的目录在每次应用程序运行时都不再相同.这就是为什么我的代码第一次运行而不能运行的原因.感谢Midhun MP.

参考:iOS8中应用容器的更改

Mid*_* MP 5

从您的注释中,您将保存核心数据中的整个路径并尝试使用该路径加载图像.

在最新的iOS版本中,每次关闭并打开应用程序时,36个字符文件夹都会发生变化.

因此,不是保存整个路径,而是保存文件名并使用以下命令检索它:

目标C.

NSString *yourImageName = @"CF7DFDB8-0A5D-4C13-9DFE-1C6C96B59DDA.png"; // Replace with actual image name
NSString *docDirPath    = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *pathForImage  = [docDirPath stringByAppendingPathComponent:yourImageName];
UIImage *imageFromFile  = [UIImage imageWithContentsOfFile:pathForImage];
Run Code Online (Sandbox Code Playgroud)

迅速:

var yourImageName = "CF7DFDB8-0A5D-4C13-9DFE-1C6C96B59DDA.png";
var docDir        = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docDirPath    = docDir[0] as? String
var pathForImage  = docDirPath!.stringByAppendingPathComponent(yourImageName)
var imageFromFile = UIImage(contentsOfFile: pathForImage)
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到详细信息技术说明TN2406:iOS 8中对应用程序容器的更改