gpt4 book ai didi

ios - 无法使用 [UIImage imageWithContentsOfFile :] and file is there 创建 UIImage

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:26:49 24 4
gpt4 key购买 nike

这个问题我google了一下,大部分用错了方法:[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];

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

------------------------我是可爱系---------------- --------------

总结:从 iOS8 开始,NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 中的目录在每次应用程序运行时不再相同。这就是为什么我的代码在第一次运行时有效而在之后不起作用的原因。感谢 Midhun 议员。

引用:Changes to App Containers in iOS8

最佳答案

根据您的评论,您正在将整个路径保存在核心数据中,并尝试使用该路径加载图像。

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

所以不要保存整个路径,只保存文件名并使用以下方法检索它:

objective-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];

swift :

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)

您可以在此处找到详细信息 Technical Note TN2406:Changes To App Containers In iOS 8

关于ios - 无法使用 [UIImage imageWithContentsOfFile :] and file is there 创建 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com