Component - Image loading from URL
This UI component shows how to load and display an image from a web address (URL) in an iOS app using Swift. It fetches the image data asynchronously and updates the screen when the image is ready.
This UI component shows how to load and display an image from a web address (URL) in an iOS app using Swift. It fetches the image data asynchronously and updates the screen when the image is ready.
UIViewController └── UIImageView
URLSession when loading an image from a URL in Swift?URLSession is used to perform network tasks like downloading data asynchronously, so the app doesn't freeze.URLSession downloads the image data in the background.URL from a string to load an image?URL(string:).let url = URL(string: "https://example.com/image.png")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data, let image = UIImage(data: data) {
print("Image loaded successfully")
} else {
print("Failed to load image")
}
}.resume()let url = URL(string: "https://example.com/image.png")
URLSession.shared.dataTask(with: url!) { data, response, error in
let image = UIImage(data: data!)
imageView.image = image
}.resume()imageView.image is set inside the background thread closure.let url = URL(string: "https://example.com/image.png")
URLSession.shared.dataTask(with: url!) { data, response, error in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
imageView.image = image
}
} else {
print("Failed to load image")
}
}.resume()DispatchQueue.main.async, which is correct.resume() to start the task.Pass the test and this pattern moves unknown