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+.
- 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
videoDestinationorvideoDestinationDirectory. Would it be better to just internally save it to the temporary directory and return that and require that they clean it up after?
- Currently, this works but requires the developer to use
- Rework code to (by default) return
[PHPickerResult], then move async mapping code toasyncstatic function to do separately (or maybe as an extension on[PHPickerResult]?)- Also add interoperability with native newer
PhotosPicker(andPhotosPickerItem/Transferable).
- Also add interoperability with native newer
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 */
}
}
}- If you'd like to support video selections, then you must use either the
setVideoDestinationDirectory(_:)orsetVideoDestinationHandler(_:)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.