Sun*_*day 43 objective-c uiimageview uiimage nsfilemanager ios
一些iOS照片相关应用程序存储使用应用程序创建的图像,而不是照片库.例如,Fat Booth显示了在应用启动时使用该应用创建的滚动列表.请注意,这些照片会在用户明确将其保存到照片库时保留.在iOS应用程序中保存和保存图像的最简单方法是什么?
我熟悉的唯一持久存储是NSUserDefaults和密钥链.但是我从来没有听说过这些用来存储大量数据,比如图像.现在我想知道核心数据是否是最简单的方法.
Tom*_*voy 65
最简单的方法是将其保存在应用程序的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);
}
Run Code Online (Sandbox Code Playgroud)
然后将imagePath保存在NSUserDefaults中的某些字典中,或者你想要的,然后检索它只需:
NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];
Run Code Online (Sandbox Code Playgroud)
Seg*_*gev 35
对于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")
}
Run Code Online (Sandbox Code Playgroud)
对于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")
}
Run Code Online (Sandbox Code Playgroud)
stringByAppendingPathComponent在Swift 2.1中不可用,因此您可以在此处使用URLByAppendingPathComponent.
获取更多信息.
您可以通过存储二进制数据来处理核心数据,但不建议这样做.有一种更好的方式 - 特别是对于照片.您的应用程序有一个只有您的应用可以访问的文档/文件目录.我建议从这里开始概念以及如何访问它.它相对简单.您可能希望将其与核心数据相结合以存储文件路径,元数据等.http://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/FileSystemOverview/FileSystemOverview.html
| 归档时间: |
|
| 查看次数: |
42236 次 |
| 最近记录: |