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 4.1 I have crated a function just pass image url, cache key after image is generated set it to completion block.
swift 3 with error handling
With Extension
Extension Usage
myImageView. setCustomImage("url")
Swift 4: A simple loader for small images (ex: thumbnails) that uses NSCache and always runs on the main thread:
Usage:
Use of Ascyimageview you can easy load imageurl in imageview.
let image1Url:URL = URL(string: "(imageurl)" as String)! imageview.imageURL = image1Url