SwiftUIPHPicker

main

SwiftUI wrapper of PhotoKit's PHPickerViewController.
edonv/SwiftUIPHPicker

SwiftUIPHPicker

SwiftUI wrapper of PhotoKit's PHPickerViewController.

The majority of the base of the code came from Hacking With Swift's post on this very topic: https://www.hackingwithswift.com/books/ios-swiftui/importing-an-image-into-swiftui-using-phpickerviewcontroller.

I added support for more than 1 selection, as well as practical extensions, and hope to extend for ease-of-use with PhotosPicker, which is only available in iOS 16+.

To-Do's

  • Add support for multiple selections.
  • Add support for selecting other Live Photos (currently only supports standard photos).
  • Add support for videos.
    • Currently, this works but requires the developer to use videoDestination or videoDestinationDirectory. Would it be better to just internally save it to the temporary directory and return that and require that they clean it up after?
  • Rework code to (by default) return [PHPickerResult], then move async mapping code to async static function to do separately (or maybe as an extension on [PHPickerResult]?)
    • Also add interoperability with native newer PhotosPicker (and PhotosPickerItem/Transferable).

Usage

import SwiftUI
import SwiftUIPHPicker

struct ContentView: View {
    @State private var showPicker = false
    
    var body: some View {
        Text("Hello world!")
            .sheet(isPresented: $showPicker) {
                PHPicker(photoLibrary: .shared()) { result in
                    switch result {
                    case .success(let selection):
                        // Process selected assets
                    case .failure(let error):
                        // Deal with error
                    }
                }
                .maxSelectionCount(5)
                .filter(.all(of: [.images, .not(.livePhotos), .videos]))
                .videoDestinationDirectory(DOCUMENT DIRECTORY) /* more code needed for this */
            }
    }
}

Notes

  • If you'd like to support video selections, then you must use either the setVideoDestinationDirectory(_:) or setVideoDestinationHandler(_:) view modifier. Without them, there won't be somewhere set to save the video file and the system's temporary file will be be deleted before it's accessible.

Description

  • Swift Tools 5.7.0
View More Packages from this Author

Dependencies

  • None
Last updated: Fri Oct 18 2024 16:47:54 GMT-0900 (Hawaii-Aleutian Daylight Time)