0

I am trying to load image from url in my ios app swift. I have written following code.

 let imageURL =  minHost + "\(userData["profileImage"])"
 let url = URL(string: imageURL)!
 let imageData = try? Data(contentsOf: url)
 profileImage.image = UIImage(data: imageData!)

Now imageURL is having proper url, but imageData receives nil and because of this, last line through an error Fatal error: Unexpectedly found nil while unwrapping an Optional value

Umair Jameel
  • 1,573
  • 3
  • 29
  • 54

5 Answers5

2

Instead of fetching image using Data(contentsOf:) method, use URLSession to perform network calls.

let imageURL =  minHost + "\(userData["profileImage"])"

if let url = URL(string: imageURL) {
    URLSession.shared.dataTask(with: url) {[weak self] (data, urlResponse, error) in
        if let data = data {
            DispatchQueue.main.async {
                self?.profileImage.image = UIImage(data: imageData)
            }
        }
    }.resume()
}

Important Note: Avoid using forced unwrapping (!) unnecessarily. It might result in unwanted app crashes. Instead use guard or if-let to unwrap optionals.

PGDev
  • 23,751
  • 6
  • 34
  • 88
1

Try this at Playground. Loading image from the URL takes some time, and need to be executed at another Thread, different from the main thread.

import UIKit

let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")!
var image = UIImage()

DispatchQueue.global().async {
    if let data = try? Data(contentsOf: url) {
        DispatchQueue.main.async {
            image = UIImage(data: data)!
        }
    }
}

image
Abjox
  • 579
  • 1
  • 4
  • 14
0

you can try like this:

        let url = URL(string: "image url here")
        if url != nil {
            DispatchQueue.global().async { [weak self] in
                if let data = try? Data(contentsOf: url!) {
                    if let image = UIImage(data: data) {
                        DispatchQueue.main.async {

                            self.profileImage.image = image

                        }
                    }
                }
            }
        }
0

Try This

let url = URL(string:imageURL)
if let data = try? Data(contentsOf: url!)
{
    profileImage.image = UIImage(data: data, scale: 1.0)!
}
steveSarsawa
  • 1,559
  • 2
  • 14
  • 31
0

Never do the downloading task on main thread. if you do, you will not able to access components in current visible screens properly. It should be always on the background thread.

    if let url = URL(string: "https://....") {

        DispatchQueue.global(qos: .background).async { 

            if let data = try? Data(contentsOf: url) {

                if let image = UIImage(data: data) {

                    DispatchQueue.main.async {

                        self.profileImage.image = image
                    }
                }
            }
        }
    }
Mahendra
  • 8,448
  • 3
  • 33
  • 56