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.
You can use pod
SDWebImage
to achieve the same. Its easy to use. Yo can get documentaion here SDWebImageHere is the sample code
If you are looking for a very very simple implementation. (This worked for me in Swift 2)
I implemented within a tableview with a custom cell that has only a image
Use this code in Swift
I wrapped the code of the best answers to the question into a single, reusable class extending UIImageView, so you can directly use asynchronous loading UIImageViews in your storyboard (or create them from code).
Here is my class:
and here is how to use it:
Xcode 8 or later • Swift 3 or later
Synchronously:
Asynchronously:
Create a method with a completion handler to get the image data from your url
Create a method to download the image (start the task)
Usage:
Extension:
Usage:
Swift 2.0 :
1)
OR
2) Add this method to VC or Extension.
Usage :