I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:
'imageWithData' is unavailable: use object construction 'UIImage(data:)'
My function:
@IBOutlet var imageView : UIImageView
override func viewDidLoad() {
super.viewDidLoad()
var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)
imageView.image = UIImage.imageWithData(data)// Error here
}
In Objective-C:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
NSData *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData: data];
_labelURL.text = @"http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png";
}
Can someone please explain me why the imageWithData:
doesn't work with Swift, and how can I solve the problem.
Github URL - https://github.com/onevcat/Kingfisher
The only things there is missing is a !
Xcode 8 • Swift 3
Leo Dabus's answer is awesome! I just wanted to provide an all-in-one function solution:
(Swift 4 update) To answer the original question directly, here's the swift equivalent of the posted Objective-C snippet.
DISCLAIMER:
It's important to note that the
Data(contentsOf:)
method will download the contents of the url synchronously in the same thread the code is being executed, so do not invoke this in the main thread of your application.An easy way to make the same code run asynchronously, not blocking the UI, is by using GCD:
That said, in real life applications, if you want to have the best User Experience and avoid multiple downloads of the same image, you may want to also have them not only downloaded, but cached. There's already quite a few libraries that does that very seamless and they are all really easy to use. I personally recommend Kingfisher:
And that's it
I recommend using Kingfisher library to download images asynchronously. The best part about using Kingfisher is, it caches all the downloaded images by default with the image url as an id. Next time when you request to download image with that particular URl, it will load it from cache.
Usage:
I have created a simple class function in my
Utils.swift
class for calling that method you can simply accesss byclassname.methodname
and your images are saved in NSCache usingImageCaching.swift
classHappy Codding. Cheers:)