Reputation: 847
I currently have the ability to take a photo or load from the camera and place an image in the UIImageView in my app be i want the ability to have a button that will save the image so when i reload the app the image is still in the UIImageView.
My though was a button to save the image once you have loaded it and in the
-(void)viewDidLoad
have the code to load the image that was saved but i don't know how to approach this.
Any help would be fantastic.
Upvotes: 1
Views: 1492
Reputation: 7341
You can convert images to NSData
using either UIImagePNGRepresentation
or UIImageJPGRepresentation
, then save the data to file calling one of NSData
's writeToFile...
methods.
Then when you restart your application, you can get the image by calling [UIImage imageWithData:[NSData dataWithContentsOfFile:filePath]]
-- EDIT --
Save image
UIImage *image = ...;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:@"image.png"];
[UIImagePNGRepresentation(image) writeToFile:cachedImagePath atomically:YES];
Load image
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:@"image.png"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:cachedImagePath]];
I used NSCachesDirectory
since I'm assuming you don't want to have this image backed up (either through iCloud or iTunes). If you do then you'd want to use NSDocumentDirectory
instead.
Upvotes: 4