download an image in swift

Here's a sample code to download an image using the URLSession and DownloadTask APIs in Swift:

main.swift
if let url = URL(string: "https://example.com/image.jpg") {
    let request = URLRequest(url: url)
    let task = URLSession.shared.downloadTask(with: request) { (url, response, error) in
        if let tempURL = url, let data = try? Data(contentsOf: tempURL), let image = UIImage(data: data) {
            // The downloaded image is now available as UIImage object.
            // Do something with the image, like displaying it in an ImageView.
            DispatchQueue.main.async {
                myImageView.image = image
            }
        }
    }
    task.resume()
}
578 chars
14 lines

This code downloads an image from the specified URL and creates a UIImage from the downloaded data. The image can then be used to update the UI or perform further processing.

gistlibby LogSnag