download an image and display it with loading state in swift

To download and display an image with a loading state in Swift, we can use the URLSession and URLSessionDownloadTask classes.

Here's an example code snippet that shows how to download an image and display it in a UIImageView with a loading spinner:

main.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var loadingSpinner: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Start the loading spinner
        loadingSpinner.startAnimating()
        
        // Create a URL for the image
        guard let url = URL(string: "https://example.com/image.jpg") else {
            return
        }
        
        // Create a URLSession download task
        let task = URLSession.shared.downloadTask(with: url) { (location, response, error) in
            
            // Check for errors
            guard error == nil, let location = location else {
                print("Error downloading image: \(error?.localizedDescription ?? "")")
                return
            }
            
            // Create a data object from the file
            let data = try? Data(contentsOf: location)
            
            // Update the UI on the main thread
            DispatchQueue.main.async {
                // Set the image in the image view
                if let imageData = data, let image = UIImage(data: imageData) {
                    self.imageView.image = image
                }
                
                // Stop the loading spinner
                self.loadingSpinner.stopAnimating()
            }
        }
        
        // Start the download task
        task.resume()
    }
}
1479 chars
47 lines

In this code, we start the spinner, create a URL for the image, and then create a URLSession download task. When the task is complete, we update the UI on the main thread by setting the image in the UIImageView and stopping the spinner.

Note that we're using try? to create a Data object from the downloaded file, which means that the data constant will be nil if there was an error while creating the object. We're also using DispatchQueue.main.async to update the UI on the main thread, since the download task operates on a background thread.

gistlibby LogSnag