Calling presentLimitedLibraryPicker from SwiftUI?

What would be the correct way of calling PHPhotoLibrary's presentLimitedLibraryPicker method from SwiftUI?

The method requires a UIViewController, which I don't have in SwiftUI. I have tried to use UIViewControllerRepresentable, and it works, but the result is that two View Controllers are presented, the one I create with UIViewControllerRepresentable, and the Limited Library Picker.

Thanks a lot in advance!

Replies

Just to add my current attempt is (It shows the picker, but when you dismiss it, you need to dismiss the extra, dummy, view controller too):

Code Block swift
import Foundation
import SwiftUI
import Photos
import PhotosUI
struct TestView: View {
    @State var showLibraryPicker = false
    var body: some View {
        NavigationView {
            VStack {
                Button("Open Library Picker") { showLibraryPicker = true }
            }
            .navigationBarTitle("Test", displayMode: .inline)
            .navigationViewStyle(StackNavigationViewStyle())
            .sheet(isPresented: $showLibraryPicker, onDismiss: { print("Dismissed") }) {
                TestLimitedLibraryPicker()
            }
        }
    }
}
struct TestLimitedLibraryPicker: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        let controller = UIViewController()
        PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: controller)
        return controller
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
    }
}


Might be too late now, but this worked for me: https://gist.github.com/JadenGeller/afb907745865052ed59c53b5ca9f8671

Update: I've just notice this Xcode debug warning when running the app:

Presenting view controller <PHPickerViewController: 0x103240080> from detached view controller <UIViewController: 0x1036bcca0> is not supported, and may result in incorrect safe area insets and a corrupt root presentation. Make sure <UIViewController: 0x1036bcca0> is in the view controller hierarchy before presenting from it. Will become a hard exception in a future release.

So it might not be a viable solution

Cheers

Gavin