在iOS设备上本地存储图像

一些iOS照片相关的应用程序将照片库以外的应用程序存储在应用程序中。 例如Fat Booth会显示在应用程序启动时使用应用程序创build的照片的滚动列表。 请注意,这些照片是持续的,而不会将用户明确保存到照片库中。 在iOS应用程序中保存和保存图像最简单的方法是什么?

我熟悉的唯一持久性商店是NSUserDefaults和关键链。 不过,我从来没有听说过这些用来存储更大的数据,如图像。 现在我想知道如果核心数据是最简单的方法。

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

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

对于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. 在这里获取更多信息。

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