Code cracker
Code cracker

Reputation: 3166

Get image from JSON data

I tried to get Image from JSON. Imagedata is printing in the console. But its displaying in the UITableViewCell.

jsonDict = [jsonArr objectAtIndex:indexPath.row];

NSLog(@"imagess%@",jsonDict);

cell.textLabel.text = [jsonDict objectForKey:@"ImageName"];
cell.textLabel.textAlignment=NSTextAlignmentRight;


NSURL *url = [NSURL URLWithString:[jsonDict objectForKey:@"ImageData"]];
NSData *imgData = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:imgData];

The code I've used to Post the image:

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:@"image/JPEG" forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];

enter image description here

Upvotes: 1

Views: 4009

Answers (2)

Basavaraj
Basavaraj

Reputation: 19

Try this code it may help you

Here imageurl is the address of the image u will accessed for JSON and Image url like http:/google/123.png and in this example cell is the UITableView Cell used in my app.

NSURL* url = [NSURL URLWithString:imageurl];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];


    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response,
                                               NSData * data,
                                               NSError * error) {
                               if (!error){
                                   cell.imagePic.image = [UIImage imageWithData: data];

                               }

                           }];

Thanks

Upvotes: 2

iphonic
iphonic

Reputation: 12719

New Answer

As per you data log, it seems that you have got the whole image there in imageData key. And that looks to me as if it is base64 encoded.

You don't need to use and URL, you need a base64 decoder, that will convert your base64 encoded string to NSData.

Please confirm with api team, whether it is encoded for Base64 or, not.

Take Base64 lib for iOS from here

And you just need to do the following

NSData *imgData = [NSData dataWithBase64EncodedString:[jsonDict objectForKey:@"ImageData"]];
cell.imageView.image = [UIImage imageWithData:imgData];

Cheers.

Upvotes: 1

Related Questions