Load UIImage from URL in iOS

Ahd Radwan picture Ahd Radwan · May 7, 2015 · Viewed 27.9k times · Source

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) {}
   ];

Answer

Ashok Londhe picture Ashok Londhe · May 7, 2015

Try this code to get image...

Code:

NSURL *url = [NSURL URLWithString:@"http://www.fnordware.com/superpng/pnggrad16rgb.png"];

NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];

[self.imageview1 setImage:image];    

Note: i have used test url. you can use your url.

Update : Swift 3.0 Code :

let url = URL(string: "http://www.fnordware.com/superpng/pnggrad16rgb.png")
    do {
        let  data = try Data(contentsOf: url!)
        var image = UIImage(data: data)
        self.imageView.image = image
        print(image)
    } catch {

    }

Note : In Xcode version 7.1 and above you need to set ATS (App Transport Security). To set ATS you need write below code in info.plist file. Make sure url of image should not be nil.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>