Adam Zarn
Adam Zarn

Reputation: 2100

Downloaded image not being displayed iOS Swift

I'm just starting to learn how to make network requests in iOS Swift. Below is a very simple image request where everything seems to be working. The task downloads the image with no errors but the imageView never displays the downloaded image. Any help would be greatly appreciated.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageURL = NSURL(string: "https://en.wikipedia.org/wiki/Baseball#/media/File:Angels_Stadium.JPG")!

        let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in
            if error == nil {
                let downloadedImage = UIImage(data: data!)
                performUIUpdatesOnMain {
                    self.imageView.image = downloadedImage
                }
            }
        }
        task.resume()
    }
}

Upvotes: 1

Views: 1335

Answers (2)

Victor Sigler
Victor Sigler

Reputation: 23451

Your code is working fine except for the fact you're using a wrong URL and for that your downloadedImage is coming nil because it can't create an UIImage for this data, the correct URL is:

https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Angels_Stadium.JPG/1920px-Angels_Stadium.JPG

Update your code code as the above code and everything should be work fine:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let imageURL = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Angels_Stadium.JPG/1920px-Angels_Stadium.JPG")!

    let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in

        guard error == nil, let data = data else { return }

        let downloadedImage = UIImage(data: data)
        dispatch_async(dispatch_get_main_queue()) {
            self.imageView.image = downloadedImage
        }
    }
    task.resume()
}

I hope this help you.

Upvotes: 3

Duncan C
Duncan C

Reputation: 131408

If you are getting an error from NSURLSession your current code would fail silently. Don't do that.

Add a print statement inside your data task's completion block that logs the value of error and of data. Also log downloadedImage once you convert data to an image.

Finally, show us the code for your performUIUpdatesOnMain function.

Upvotes: 1

Related Questions