Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Some iOS photo-related apps store images created with the app somewhere other than the photo library. For example Fat Booth shows a scrolling list of photos created with the app at app start-up. Note these photos are persisted w/o the user explicitly saving them to the photo library. What is the simplest way to save and persist images inside an iOS application?

The only persistent stores I'm familiar with are NSUserDefaults and the key chain. However I've never heard of these used to store larger pieces of data such as an image. Now I'm wondering if Core Data is the easiest way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
454 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...