Skip to content

Instantly share code, notes, and snippets.

@oalansari82
Last active March 21, 2023 04:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oalansari82/b00371fc81a21a64ce58e27501c3c7de to your computer and use it in GitHub Desktop.
Save oalansari82/b00371fc81a21a64ce58e27501c3c7de to your computer and use it in GitHub Desktop.
PHPicker multi image selection SwiftUI Implementation
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 ?? "")
}
}
}
}
}
}
}
@asemelkhouli20
Copy link

It’s already on main thread

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment