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.
Swift 2.x answer that downloads image to file (as opposed to Leo Dabus's answer, which stores the image in memory). Based on Leo Dabus's answer and Rob's answer from Get the data from NSURLSession DownloadTaskWithRequest from completion handler:
Swift 4::
This will shows loader while loading the image. You can use NSCache which store image temporarily
Usage:-
If you just want to load image (Asynchronously!) - just add this small extension to your swift code:
And use it this way:
Swift 2 with error Handle and custom request header
Simply add extension to UIImageView:
And then, use the new
imageFromUrl(urlString: String)
to download imageUsage:
Here is Working code for Loading / Downloading image from URL. NSCache automatically and Display Placeholder image before download and Load Actual image (Swift 4 Code).
Use Like this :
Swift 2.2 || Xcode 7.3
It provides multiple features like:
and very easy to implement for your app
Step.1 Install pods
Alamofire 3.3.x
AlamofireImage 2.4.x
Step.2 import and Use
that's it!! it will take care everything
Great thanks to Alamofire guys, for making iDevelopers life easy ;)