Can I load a UIImage from a URL?
Solution 1:
You can do it this way (synchronously, but compact):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
A much better approach is to use Apple's LazyTableImages to preserve interactivity.
Solution 2:
You can try SDWebImage, it provides:
- Asynchronous loading
- Caching for offline use
- Place holder image to appear while loading
- Works well with UITableView
Quick example:
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Solution 3:
And the swift version :
let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData)
Solution 4:
If you're really, absolutely positively sure that the NSURL is a file url, i.e. [url isFileURL]
is guaranteed to return true in your case, then you can simply use:
[UIImage imageWithContentsOfFile:url.path]
Solution 5:
get DLImageLoader and try folowing code
[DLImageLoader loadImageFromURL:imageURL
completed:^(NSError *error, NSData *imgData) {
imageView.image = [UIImage imageWithData:imgData];
[imageView setContentMode:UIViewContentModeCenter];
}];
Another typical real-world example of using DLImageLoader, which may help someone...
PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
@"http://graph.facebook.com/%@/picture?type=large",
[aFacebookUser objectForKey:@"id"] ];
__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
completed:^(NSError *error, NSData *imgData)
{
if ( loadMe == nil ) return;
if (error == nil)
{
UIImage *image = [UIImage imageWithData:imgData];
image = [image ourImageScaler];
loadMe.image = image;
}
else
{
// an error when loading the image from the net
}
}];
As I mention above another great library to consider these days is Haneke (unfortunately it's not as lightweight).