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 in order to create a UIViewController, and it works, but the result is that two View Controllers are presented, the one I create with UIViewControllerRepresentable, and the Limited Library Picker.
Both View Controllers need to be dismissed in order to get to the original screen, which is not desirable.
To sum up the issue I see:
- presentLimitedLibraryPicker works by passing a ViewController.
- This makes me create and present a dummy ViewController, just so I can call the method.
- There's no way to obtain a reference to the Limited Library Picker, also it doesn't offer a delegate. So I can't detect when the Limited Library Picker controller is dismissed.
This is my attempt (It shows the picker, but when you dismiss it, you need to dismiss the extra, dummy, view controller too:
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) {
}
}
Here is some demo approach. Prepared & tested with Xcode 12 / iOS 14.