Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Use the SwiftUI PhotosPicker
Written by Team Kodeco

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.
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:

  • A ZStack which layers a ScrollView for displaying the images and a PhotosPicker view for selecting images.
  • The LazyVGrid within the ScrollView presents the selected images in a flexible grid layout.
  • The task modifier, combined with Swift’s async/await syntax, provides an elegant solution to load images asynchronously as the selectedItems changes.
  • The loadImages(from:) function is marked as async and uses a do-catch block to handle potential errors when loading images, making error handling cleaner and more explicit.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.