الثلاثاء، 24 ديسمبر 2013

How to extract image from JSON response in iOS

For extercating the Photo name from the JASON response you can use this code

JSONResponse : [ { "photo": "23_841676772.jpg", "date": "2013-06-06 08:11:15", "tags": "", "ID_article": "1", "commentcount": "5" },]

Make a Array object in .h file

@interface ViewController : UIViewController{ NSMutableArray * photoNameData;}

And in .m file

photoNameData =[[NSMutableArray alloc] init];NSMutableArray * tmpAry = JSONResponse;if (tmpAry.count !=0) { for (int i=0; iAnd than in Your cell code

if (photoNameData.count !=0) { cell.blogImageView.image = [UIImage imageNamed:[photoNameData objectAtIndex:indexPath.row]];}


You can use the code below to download the image in document directory.

//First check that document directory contain image or not NSString* tmpImgURL = @"http://www.my server.com/web_services/photos/23_841676772.jpg"; //for the image you need URL NSString* tmpStr = @"23_841676772.jpg"; //You can use code above to get image name 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); } }]; }

And you can use this image using this code..

NSString* tmpStr = @"23_841676772.jpg"; //You can use code above to get image nameNSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];UIImage * image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",documentsDirectoryPath, tmpStr]];

View the original article here

ليست هناك تعليقات:

إرسال تعليق