要从 JASON 响应中提取照片名称,您可以使用此代码
JSONResponse : [
{ "photo": "23_841676772.jpg",
"date": "2013-06-06 08:11:15",
"tags": "",
"ID_article": "1",
"commentcount": "5"
},
]
在.h 文件中创建一个数组对象
@interface ViewController : UIViewController
{
NSMutableArray * photoNameData;
}
在.m 文件中
photoNameData =[[NSMutableArray alloc] init];
NSMutableArray * tmpAry = JSONResponse;
if (tmpAry.count !=0) {
for (int i=0; i<tmpAry.count; i++) {
NSMutableDictionary * tmpDictn = [tmpAry objectAtIndex:i];
[photoNameData addObject:[tmpDictn objectForKey:@"photo"]];
}
}
您可以使用以下代码下载文档目录中的图片。
for (int i=0; i<photoNameData.count; i++) { //updated here
//First check that document directory contain image or not
NSString* tmpStr = [photoNameData objectAtIndex:i]; // used the photoNameData to get image name
NSString* tmpImgURL = [NSString stringWithFormat:@"%@%@",@"http://www.my server.com/web_services/photos/",tmpStr]; //merge the image name and url
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString* foofile = [documents stringByAppendingPathComponent:tmpStr];
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
// if image not exist than download it
if (!imageExists) {
NSLog(@"%@ not exist",tmpImgURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tmpImgURL] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10.0];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *err){
if (!err && data) {
//NSLog(@"data : %@",data);
NSString *finalPath = [documents stringByAppendingPathComponent:tmpStr];
NSLog(@"finalPath : %@",finalPath);
[data writeToFile:finalPath atomically:YES];
}else{
NSLog(@"err : %@",err);
}
}];
}
}
您可以使用此代码使用此图像..
NSString* tmpStr = [photoNameData objectAtIndex:indexPath.row]; //get the image name from photoNameData
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",documentsDirectoryPath, tmpStr]];
cell.blogImageView.image = image;