Search code examples
iphoneiosios6uiimageviewnsdata

Display Image to UIImageView which comes from Server


I am getting strange issue please if get help from anyone then it'll be appreciated.

My problem is i am getting only Image names from server through web service for ex: abc.png.

Now that image need to be attached with the static URL & than it will be used to display to UIImageView.

I have used this code:

for (int i = 0; i<[[myDic valueForKey:@"posts"] count]; i++)
{
    NSData *bgImageData = nil;
    if ([[[[myDic valueForKey:@"posts"] objectAtIndex:i] valueForKey:@"post"] valueForKey:@"video_image"] == [NSNull null])
    {
        bgImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://drupal.org/files/issues/no-pre.png"]];
    }
    else
    {
        bgImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://sitebildz.com/application/document/video/%@",[[[[myDic valueForKey:@"posts"] objectAtIndex:i] valueForKey:@"post"] valueForKey:@"video_image"]]]];
    }
    [arrVideoImage addObject:bgImageData];
}

For Display in Table :

cell.imageView.image = [UIImage imageWithData:[arrVideoImage objectAtIndex:indexPath.row]];

But don't know why its not working.

Thanks.


Solution

  • You're doing wrong. See you're making NSData in loop. Do you think it will wait until image is download from server ??? Nope it will not wait. So in this case you're adding empty NSData.

    Would be better to use SDWebImage.
    1. Download it
    2. Import it in your project
    3. build project (success)
    4. Import #import "UIImageView+WebCache.h" in your ViewController class

    [cell.imageView setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeHolderImageName"]];