在iOS设备上本地存储图像

时间:2013-01-25 23:24:04

标签: ios objective-c uiimageview uiimage nsfilemanager

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

我熟悉的唯一持久存储是NSUserDefaults和密钥链。但是我从来没有听说过这些用来存储大量数据,比如图像。现在我想知道核心数据是否是最简单的方法。

3 个答案:

答案 0 :(得分:64)

最简单的方法是将其保存在应用程序的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];

答案 1 :(得分:34)

对于Swift:

let imageData = UIImagePNGRepresentation(selectedImage)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let imagePath = paths.stringByAppendingPathComponent("cached.png")

if !imageData.writeToFile(imagePath, atomically: false)
{
   println("not saved")
} else {
   println("saved")
   NSUserDefaults.standardUserDefaults().setObject(imagePath, forKey: "imagePath")
}

对于Swift 2.1:

let imageData = UIImagePNGRepresentation(selectedImage)
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let imageURL = documentsURL.URLByAppendingPathComponent("cached.png")

if !imageData.writeToURL(imageURL, atomically: false)
{
    print("not saved")
} else {
    print("saved")
    NSUserDefaults.standardUserDefaults().setObject(imageData, forKey: "imagePath")
}
Swift 2.1中无法使用

stringByAppendingPathComponent,因此您可以使用URLByAppendingPathComponent. 获取更多信息here.

答案 2 :(得分:6)

可以通过存储二进制数据来执行核心数据,但不推荐。有一种更好的方式 - 特别是对于照片。您的应用程序有一个只有您的应用可以访问的文档/文件目录。我建议从这里开始概念以及如何访问它。它相对简单。您可能希望将其与核心数据相结合,以存储文件路径,元数据等。http://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/FileSystemOverview/FileSystemOverview.html

相关问题