Contents

PhotosPicker

A view that displays a Photos picker for choosing assets from the photo library.

Declaration

@MainActor @preconcurrency struct PhotosPicker<Label> where Label : View

Overview

Use the Photos picker view to browse and select images and videos from the photo library. The view contains methods for single selection and multiple selection. For example, the following code displays a button that — when pressed — shows a picker in multiple selection mode.

import SwiftUI
import PhotosUI

struct PhotosSelector: View {
    @State var selectedItems: [PhotosPickerItem] = []

    var body: some View {
        PhotosPicker(selection: $selectedItems,
                     matching: .images) {
            Text("Select Multiple Photos")
        }
    }
}

When displaying the picker, you can use PHPickerFilter options to customize what it displays. For example, the following code displays images and excludes screenshots.

PhotosPicker(selection: $selectedItems,
             matching: .any(of: [.images, .not(.screenshots)])) {
    Text("Select Photos")
}

The selection results you get are placeholder objects. A PhotosPickerItem conforms to Transferable, and allows you to load a representation you request. To load a SwiftUI Image and track progress, use loadTransferable(type:completionHandler:).

func loadTransferable(from imageSelection: PhotosPickerItem) -> Progress {
    return imageSelection.loadTransferable(type: Image.self) { result in
        DispatchQueue.main.async {
            guard imageSelection == self.imageSelection else { return }
            switch result {
            case .success(let image?):
                // Handle the success case with the image.
            case .success(nil):
                // Handle the success case with an empty value.
            case .failure(let error):
                // Handle the failure case with the provided error.
            }
        }
    }
}

A failure can occur when the system attempts to retrieve the data. For example, if the picker tries to download data from iCloud Photos without a network connection.

Topics

Creating a picker

Creating a picker with a title

See Also

Photos picker for SwiftUI