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.swift1479 chars47 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