show image from url in swift

To show an image from a URL in Swift, follow these steps:

  1. Create a URL object with the URL of the image you want to load.
main.swift
guard let url = URL(string: "https://example.com/image.png") else { return }
77 chars
2 lines
  1. Create a URLSession object to download the image data.
main.swift
let session = URLSession.shared
32 chars
2 lines
  1. Create a data task with the URL and implement the completion handler to handle the image data.
main.swift
let dataTask = session.dataTask(with: url) { (data, response, error) in
    if let error = error {
        print("Error: \(error.localizedDescription)")
        return
    }
    
    if let data = data, let image = UIImage(data: data) {
        // handle the image
    }
}
273 chars
11 lines
  1. Start the data task.
main.swift
dataTask.resume()
18 chars
2 lines
  1. Handle the image by updating a UIImageView with the loaded image.
main.swift
DispatchQueue.main.async {
    imageView.image = image
}
57 chars
4 lines

Putting it all together in a function:

main.swift
func loadAndShowImage(from urlString: String, into imageView: UIImageView) {
    guard let url = URL(string: urlString) else { return }
    
    let session = URLSession.shared
    
    let dataTask = session.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }
        
        if let data = data, let image = UIImage(data: data) {
            DispatchQueue.main.async {
                imageView.image = image
            }
        }
    }
    
    dataTask.resume()
}
585 chars
21 lines

You can call this function passing a URL string and a UIImageView to display the loaded image:

main.swift
loadAndShowImage(from: "https://example.com/image.png", into: imageView)
73 chars
2 lines

gistlibby LogSnag