0

could you please provide me by sample code for creation a UIImage object with specific width and height programmatically in the code then load an Image in it which supposed to fetch from json (it has to be an image URL).

If I use synchronous network request for loading the picture does it block my UI till loading be completed or not? if so what's the solution?

Thanks in Advance

1 Answer 1

1

Pull out the image URL from your json data, download the image, and then use the image as needed.

NSString *imageURL = url from your json string;
NSURL *url = [NSURL URLWithString:imageURL];
UIImageView *imageView = [UIImageView alloc] initWithFrame:CGRectMake(0,0,50,75)];
[yourParentView addSubview: imageView];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
    dispatch_sync(dispatch_get_main_queue(), ^{
        imageView.image = image;
        CGRect frame = CGRectMake(imageView.origin.x, imageView.origin.y, image.size.width, image.size.height);
        imageView.frame = frame;
    });
});
3
  • Thanks for your answer just where and how can I specify width and height of the imageView? Commented Jun 13, 2013 at 17:18
  • 2.when I copy this code I have this error: 'use of undeclared identifier queue' Commented Jun 13, 2013 at 18:28
  • You won't know the size until you download the image. But you could specify a size for your UIImageView and then change it when you received your image. I've updated my answer.
    – bbarnhart
    Commented Jun 13, 2013 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.