QuentR QuentR - 4 years ago 5371
Swift Question

Loading image from URL

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() {


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.


Answer Source

Xcode 7.1 Swift 2.1


if let filePath = NSBundle.mainBundle().pathForResource("imageName", ofType: "jpg"), image = UIImage(contentsOfFile: filePath) {
    imageView.contentMode = .ScaleAspectFit
    imageView.image = image


Create a function to get the data from your url

func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        completion(data: data, response: response, error: error)

Create a function to download the image (start the task)

func downloadImage(url: NSURL){
    print("Download Started")
    print("lastPathComponent: " + (url.lastPathComponent ?? ""))
    getDataFromUrl(url) { (data, response, error)  in
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
            print(response?.suggestedFilename ?? "")
            print("Download Finished")
            imageView.image = UIImage(data: data)


override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.
    println("Begin of code")
    if let checkedUrl = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
        imageView.contentMode = .ScaleAspectFit
    println("End of code. The image will continue downloading in the background and it will be loaded when it ends.")

or as an Extension:

extension UIImageView {
    func downloadedFrom(link link:String, contentMode mode: UIViewContentMode) {
            let url = NSURL(string: link)
            else {return}
        contentMode = mode
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
                let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
                let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
                let data = data where error == nil,
                let image = UIImage(data: data)
                else { return }
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                self.image = image
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download