0
0
iOS Swiftmobile~5 mins

Image loading from URL in iOS Swift

Choose your learning style9 modes available
Introduction

Loading images from a URL lets your app show pictures from the internet. This makes your app dynamic and fresh.

Showing user profile pictures from a web service
Displaying product images in a shopping app
Loading photos from a social media feed
Showing banners or ads that update remotely
Syntax
iOS Swift
let url = URL(string: "https://example.com/image.png")
URLSession.shared.dataTask(with: url!) { data, response, error in
  if let data = data {
    DispatchQueue.main.async {
      imageView.image = UIImage(data: data)
    }
  }
}.resume()

Use URLSession to download image data asynchronously.

Update UI on the main thread using DispatchQueue.main.async.

Examples
Basic example to load an image from a URL and set it to an UIImageView.
iOS Swift
let url = URL(string: "https://example.com/photo.jpg")
URLSession.shared.dataTask(with: url!) { data, _, _ in
  if let data = data {
    DispatchQueue.main.async {
      imageView.image = UIImage(data: data)
    }
  }
}.resume()
Example with error handling and safe URL unwrapping.
iOS Swift
guard let url = URL(string: "https://example.com/pic.png") else { return }
URLSession.shared.dataTask(with: url) { data, _, error in
  if let error = error {
    print("Error loading image: \(error)")
    return
  }
  if let data = data {
    DispatchQueue.main.async {
      imageView.image = UIImage(data: data)
    }
  }
}.resume()
Sample App

This app shows a 200x200 placeholder image loaded from the internet inside an image view positioned at (50, 100) on the screen.

iOS Swift
import UIKit

class ViewController: UIViewController {
  let imageView = UIImageView()

  override func viewDidLoad() {
    super.viewDidLoad()
    imageView.frame = CGRect(x: 50, y: 100, width: 200, height: 200)
    imageView.contentMode = .scaleAspectFit
    view.addSubview(imageView)

    guard let url = URL(string: "https://via.placeholder.com/200") else { return }
    URLSession.shared.dataTask(with: url) { data, _, error in
      if let error = error {
        print("Failed to load image: \(error)")
        return
      }
      if let data = data {
        DispatchQueue.main.async {
          self.imageView.image = UIImage(data: data)
        }
      }
    }.resume()
  }
}
OutputSuccess
Important Notes

Always load images asynchronously to avoid freezing the app.

Remember to update UI elements on the main thread.

Consider caching images for better performance in real apps.

Summary

Use URLSession to download image data from a URL.

Update the UIImageView on the main thread after loading.

Handle errors and invalid URLs safely.