我从网上检索图像及其信息(来源和其他一些信息)。我该怎么把它存放在iPhone上?我看到使用NSFileManager存储图像,但是如何用图像存储图像和其他信息?我应该使用NSDictionary和键 - 像,源,信息,然后将该字典存储到NSMutableArray然后将该数组存储到NSFileManager ??或者还有其他方式吗?访问这些保存的图像和相应信息的小提示会很好。
感谢。
答案 0 :(得分:1)
// 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"]]);
}
答案 1 :(得分:0)
有很多方法可以满足您的要求
1)SQLITE:将图像元数据与文件名一起保存在一个表中
2)NSUserDefaults:如果图像数量相当少
3)文本文件:用新行分隔数据,这也应该不难,再次取决于你的要求。
希望这有帮助。
答案 2 :(得分:0)
你绝对应该像这样使用CoreData和app documents文件夹:
如果你只是一次下载图像,我认为这是最好和最简单的方法。
如果你想下载不同的图像或更新图像你可以使用相同的过程,提到不应该将图像保存在文档文件夹中,你只需要使用AsyncImageDownload库(很多)下载图像,您必须将图像URL存储在数据库中。