在 iOS 设备上本地存储图像

2024-03-06

一些 iOS 照片相关应用程序会将使用该应用程序创建的图像存储在照片库之外的其他位置。例如,Fat Booth 在应用程序启动时显示使用该应用程序创建的照片的滚动列表。请注意,这些照片将被保留,而无需用户明确将它们保存到照片库中。在 iOS 应用程序中保存和保留图像的最简单方法是什么?

我唯一熟悉的持久性存储是 NSUserDefaults 和钥匙链。然而,我从未听说过它们用于存储较大的数据,例如图像。现在我想知道核心数据是否是最简单的方法。


最简单的方法是将其保存在应用程序的 Documents 目录中,并使用 NSUserDefaults 保存路径,如下所示:

NSData *imageData = UIImagePNGRepresentation(newImage);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];

NSLog(@"pre writing to file");
if (![imageData writeToFile:imagePath atomically:NO]) 
{
    NSLog(@"Failed to cache image data to disk");
}
else
{
    NSLog(@"the cachedImagedPath is %@",imagePath); 
}

然后将 imagePath 保存在 NSUserDefaults 中的某个字典中,或者以您想要的方式保存,然后检索它只需执行以下操作:

 NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 iOS 设备上本地存储图像 的相关文章

随机推荐