43 - Use the SwiftUI PhotosPicker

SwiftUI provides a powerful tool for browsing and selecting images and videos from the photo library: the PhotosPicker view. This component seamlessly blends into your iOS app and offers both single and multiple selection capabilities. This section demonstrates how to leverage PhotosPicker by creating a photo gallery app. The app will select images from the device’s photo library and present them in a grid layout.

To begin with, import the necessary frameworks: SwiftUI and PhotosUI.

import SwiftUI
import PhotosUI

Next, create the ContentView:

struct ContentView: View {
  @State private var selectedItems = [PhotosPickerItem]()
  @State private var images = [UUID: Image]()

  var body: some View {
    ZStack {
      ScrollView {
        LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))]) {
          ForEach(Array(images.keys), id: \.self) { key in
            images[key]!
              .resizable()
              .scaledToFill()
              .frame(width: 100, height: 100)
              .clipped()
          }
        }
      }

      VStack {
        Spacer()
        PhotosPicker(selection: $selectedItems, matching: .images) {
          Text("Select Images")
        }
        .task(id: selectedItems, {
          await loadImages(from: selectedItems)
        })
        Spacer()
      }
    }
  }

  private func loadImages(from items: [PhotosPickerItem]) async {
    for item in items {
      do {
        let image = try await item.loadTransferable(type: Image.self)
        if let image = image {
          images[UUID()] = image
        }
      } catch {
        print("Failed to load image: \(error)")
      }
    }
  }
}

After you tap Select Images, your preview should look like this:

Use PhotosPicker to let your user select photos or videos.

This example showcases an effective way to create an interactive photo picker using SwiftUI. Key points include:

With the ability to select images from your photo library and present them directly within your SwiftUI app, this example illustrates a practical real-world application of SwiftUI’s PhotosPicker