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?
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/"]
One way to do this is use the application's document directory. This is specific to a application and will not be visible to other applications.
How to create this:
Just add a static function to App Delegate and use the function where ever the path is required.
- (NSString )applicationDocumentDirectory {
/
Returns the path to the application's documents directory.
*/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
Hope it Helped..
I think this("iphone-user-defaults-and-uiimages") post addresses your issue. Don't save blobs to a property list such as NSUserDefaults. In your case I would write to disk directly instead.