iCodes
iCodes

Reputation: 1457

How to extract image from JSON response in iOS

I am parsing JSON from a webService which gives me image , text , etc.The text can be extracted , but how do I get the image out of it?

This is how the JSON response looks like.

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

And I was trying to set it like this in tableView:cellForRow method which doesn't work.

    NSMutableDictionary *tempDict3 = [self.jsonArray objectAtIndex:indexPath.row];
    cell.blogImageView.image = [UIImage imageNamed:[tempDict3 objectForKey:@"photo"]];

Upvotes: 0

Views: 2558

Answers (3)

Dilip Manek
Dilip Manek

Reputation: 9143

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; i<tmpAry.count; i++) {
            NSMutableDictionary * tmpDictn = [tmpAry objectAtIndex:i];
            [photoNameData addObject:[tmpDictn objectForKey:@"photo"]];
        }
    }


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

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

And you can use this image using this code..

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;

Upvotes: 1

Charan Giri
Charan Giri

Reputation: 1097

ask your web service team to add another tag as "image_url" to your response so that you can convert the image url to image. If they say we can't give it for security reason, then the only option left is hard code the path and append the "image name" to it so that you will have complete url of image and now you can convert it into image.

Upvotes: 1

Mehmood
Mehmood

Reputation: 931

I have used static json you can replace str with your json url.

NSString *Str =[NSString stringWithFormat:@"[{\"photo\": \"23_841676772.jpg\",\"date\":\"2013-06-06 08:11:15\",\"tags\": \"\",\"ID_article\": \"1\",\"commentcount\": \"5\"},{\"photo\": \"dfdgfdgd.jpg\",\"date\":\"2013-06-06 08:11:15\",\"tags\": \"\",\"ID_article\": \"1\",\"commentcount\": \"5\"}]"];


NSDictionary *catgDict = [NSJSONSerialization JSONObjectWithData:[Str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];

for(NSDictionary *dict in catgDict)
{
    NSLog(@"dd: %@",dict);
    NSLog(@"Photo: %@",[dict valueForKey:@"photo"]);
}

Upvotes: 1

Related Questions