Search code examples
ioswebuiimageviewgrand-central-dispatchdispatch

Loading image in to UIImageView in dispatch not working


I'm working with a UICollectionView and I need to load images in to the collection cell.

Here is the code

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSURL *imageURL = [NSURL URLWithString:post.cover_img_url];
        NSData *data = [NSData dataWithContentsOfURL:imageURL];
        UIImage *image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.cover_img setImage:image];
        });
    });


post.cover_img_url = the_url_for_the_image;
cell.cover_img = the_UIImageView_object;

When I set the image not from the web, it works perfectly.

But when I try from the web, the UIImageView is blank not image.

Anyone have any ideas?


Solution

  • Your code looks like it should be working, but there are a couple of things that you need to test. First, you need to check to make sure that imageURL is both non-nil, and points to exactly where you think it's pointing. Copy paste a log result to your desktop browser if you have to.

    NSLog(@"%@",imageURL);
    

    Second, in the event that fetching the image fails, you need to be able to detect this. I recommend that if you continue to use the dataWithContentsOfURL: route that you at least use the following to check the error:

    NSError *error = NULL;
    NSData *data = [NSData dataWithContentsOfURL:imageURL options:NSDataReadingMappedIfSafe error:&error];
    
    if (error) {
        // ...
    }