I am making a small app where the user can create a game profile, input some data and a picture that can be taken with the camera.
I save most of that profile data with the help of NSUserDefaults
, but a friend discouraged me from saving the profile image in NSUserDefault
.
What's the proper way to save and retrieve images locally in my app?
Right-click the illustration that you want to save as a separate image file, and then click Save as Picture. In the Save as type list, select the file format that you want.
You should save it in Documents
or Cache
folder. Here is how to do it.
Saving into Documents
folder:
NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"];
BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!ok)
{
NSLog(@"Error creating file %@", path);
}
else
{
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
[myFileHandle closeFile];
}
Loading from Documents
folder:
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
You can also use UIImageJPEGRepresentation
to save your UIImage
as a JPEG
file. What's more if you want to save it in Cache
directory, use:
[NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With