Andre
Andre

Reputation: 7648

iOS Objective-c: how to set and ImageView from an URL

Evening, I'm trying to set an ImageView.image (an IBOutlet in this case) with an image downloaded from the web.

I've already ridden a lot of questions about this in stack overflow.

And I've found this common answer:

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

 NSData *data = [NSData dataWithContentsOfURL:url];

 NSLog(@"imageData: %@", data);

 UIImage *image = [UIImage imageWithData:data];

 NSLog(@"image: %@", image);

 self.imageView.image = image;

But of course in my case does not work. My logs are always null.

Can you please tell me which is the problem?

Upvotes: 0

Views: 2374

Answers (3)

Deepak Kumar Sahu
Deepak Kumar Sahu

Reputation: 453

This URL is HTTP type so you need to set NSAppTransportSecurity at your plist file.

For that process is

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

enter image description here

This might help you. Please let me know if having any problem regarding this.

Upvotes: 3

Sunny Do
Sunny Do

Reputation: 11

you should use SDWebImage library. It can cache image from url also. and use very simple

[yourImageView sd_setImageWithURL:[NSURL URLWithString:@"image-url"] placeholderImage:[UIImage imageNamed:@"photo.jpg"]]

place holder image is showed in case the image hasn't load yet.

Upvotes: 1

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

I believe you are trying to run it on iOS 8 +

Please add this to your info.plist

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

And everything should be fine :)

WHY ??

iOS 8 onwards http is not allowed you have to use either https or add exception to your info.plist :)

Upvotes: 2

Related Questions