且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在iOS设备上本地存储图像

更新时间:2023-02-02 21:01:19

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

The simplest way is to save it in the app's Documents directory and save the path with NSUserDefaults like so:

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的某些字典中,或者你想要的,然后检索它只需:

Then save the imagePath in some dictionary in NSUserDefaults or however you'd like, and then to retrieve it just do:

 NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];