I retrieve image and its information (origin and some other info) from web. How can I store that on iPhone ? I saw using NSFileManager for storing images, but how can I store image and some other information with it ? Should I use NSDictionary and keys like - image, origin, info and then store that dictionary to NSMutableArray and then store that array to NSFileManager ?? Or is there some other way ? And small hint on accessing those saved images and corresponding information would be nice.
Thanks.
// Download Image from Remote Server
NSURL *url = [NSURL URLWithString:@"Your IMAGE URL HERE"];
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"moon" ofType:@"jpg"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libPath = [paths objectAtIndex:0];
NSString *filePath = [libPath stringByAppendingPathComponent:[url lastPathComponent]];
BOOL status = [data writeToFile:filePath atomically:YES];
// Save Image file to Library Directory, if success then store infor about it in file
if(status)
{
// If File Exist then read it otherwise creat new
NSMutableDictionary *imageInfoDict;
if([[NSFileManager defaultManager] fileExistsAtPath:[libPath stringByAppendingPathComponent:@"imageInfo.plist"]])
{
NSData *fileData = [NSData dataWithContentsOfFile:[libPath stringByAppendingPathComponent:@"imageInfo.plist"]];
imageInfoDict = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:fileData]];
// To set As Background Load image from disc
// Read filename from Dictionary, but you must know the key which you want to get
NSString *fileName = imageInfoDict[@"68051_10151509108346729_1731694342_s.png"][@"imagePath"];
// Set your image as background
UIImage *image = [UIImage imageWithContentsOfFile:[libPath stringByAppendingPathComponent:fileName]];
}
else
imageInfoDict = [NSMutableDictionary dictionaryWithCapacity:0];
// Create Dictionary to store Single Image Info
NSDictionary *imageInfo = [NSDictionary dictionaryWithObjectsAndKeys:[url lastPathComponent], @"imagePath",
[url lastPathComponent], @"imageName",
[NSDate date], @"date",nil];
// Add Single Image Info to Main Dictionary
[imageInfoDict setValue:imageInfo forKey:[url lastPathComponent]];
// Convert Main info Dictionary to `NSData` to Save on Disc
NSData *fileData = [NSKeyedArchiver archivedDataWithRootObject:imageInfoDict];
// Save file to Disc
[fileData writeToFile:[libPath stringByAppendingPathComponent:@"imageInfo.plist"] atomically:YES];
// Read Info From File
NSLog(@"%@",[NSDictionary dictionaryWithContentsOfFile:[libPath stringByAppendingPathComponent:@"imageInfo.plist"]]);
}