PHPicker multi image selection SwiftUI Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import PhotosUI | |
struct PhotoPicker: UIViewControllerRepresentable { | |
typealias UIViewControllerType = PHPickerViewController | |
@Binding var images: [UIImage] | |
var selectionLimit: Int | |
var filter: PHPickerFilter? | |
var itemProviders: [NSItemProvider] = [] | |
func makeUIViewController(context: Context) -> PHPickerViewController { | |
var configuration = PHPickerConfiguration() | |
configuration.selectionLimit = self.selectionLimit | |
configuration.filter = self.filter | |
let picker = PHPickerViewController(configuration: configuration) | |
picker.delegate = context.coordinator | |
return picker | |
} | |
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { | |
} | |
func makeCoordinator() -> Coordinator { | |
return PhotoPicker.Coordinator(parent: self) | |
} | |
class Coordinator: NSObject, PHPickerViewControllerDelegate, UINavigationControllerDelegate { | |
var parent: PhotoPicker | |
init(parent: PhotoPicker) { | |
self.parent = parent | |
} | |
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { | |
//Dismiss picker | |
picker.dismiss(animated: true) | |
if !results.isEmpty { | |
parent.itemProviders = [] | |
parent.images = [] | |
} | |
parent.itemProviders = results.map(\.itemProvider) | |
loadImage() | |
} | |
private func loadImage() { | |
for itemProvider in parent.itemProviders { | |
if itemProvider.canLoadObject(ofClass: UIImage.self) { | |
itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in | |
if let image = image as? UIImage { | |
self.parent.images.append(image) | |
} else { | |
print("Could not load image", error?.localizedDescription ?? "") | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment