Storing images locally on an iOS device

与世无争的帅哥 提交于 2019-11-26 21:33:04
Tommy Devoy

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); 
}

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

For 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")
}

For 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")
}

stringByAppendingPathComponent is unavailable in Swift 2.1 so you can use URLByAppendingPathComponent. Get more info here.

You can do it with core data by storing binary data, but its not recommended. There is a much better way - especially for photos. Your application has a documents/file directory that only your app can access. I recommend starting here for the concepts and how to access it. Its relatively straightforward. You may want to combine this with core data to store file paths, metadata, etc. http://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/FileSystemOverview/FileSystemOverview.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!