Search code examples
iosobjective-cswift3nsurlrequestimageurl

Load UIImage from URL in iOS


I am trying to load a UIImage from its URL with completionand placeholder image , but neither the UIImage nor the placeholder UIImage are loaded.

Here is my code:

  NSURL *url = [NSURL URLWithString:@"http://assets.gearlive.com/tvenvy/blogimages/stewiegriffin.jpg"];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];

  [self.imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"bg.png"]

      success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
          imageView.image = image;
      } 
      failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {}
   ];

Solution

  • Use AFnetworking where you can set placeholder image also if the url is not correct. This is more efficient when you are loading images in a tableview or a collection view.

    Import UIImageView+AFNetworking.h

    #import "UIImageView+AFNetworking.h"
    

    and us the following code:

    NSString *url1=@"http://www.fnordware.com/superpng/pnggrad16rgb.png";
    [self.image setImageWithURL:[NSURL URLWithString:url1] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 
    

    You can download it from gitHub