Guest User

Untitled

a guest
Jan 10th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.33 KB | None | 0 0
  1. import PhotosUI
  2. import SwiftUI
  3.  
  4.  
  5.  
  6. struct ImagePicker: UIViewControllerRepresentable {
  7.     @Binding var image: UIImage?
  8.    
  9.     class Coordinator: NSObject, PHPickerViewControllerDelegate {
  10.            
  11.         var parent: ImagePicker
  12.        
  13.         init (_ parent: ImagePicker) {
  14.             self.parent = parent
  15.         }
  16.        
  17.         func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
  18.             picker.dismiss(animated: true)
  19.            
  20.             guard let provider = results.first?.itemProvider else { return }
  21.  
  22.             if provider.canLoadObject(ofClass: UIImage.self) {
  23.                 provider.loadObject(ofClass: UIImage.self) { image, _ in
  24.                     self.parent.image = image as? UIImage
  25.                 }
  26.             }
  27.         }
  28.     }
  29.    
  30.     func makeUIViewController(context: Context) -> PHPickerViewController {
  31.         var config = PHPickerConfiguration()
  32.         config.filter = .images
  33.        
  34.         let picker = PHPickerViewController(configuration: config)
  35.         picker.delegate = context.coordinator
  36.         return picker
  37.     }
  38.    
  39.     func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
  40.     }
  41.    
  42.     func makeCoordinator() -> Coordinator {
  43.         Coordinator(self)
  44.     }
  45.        
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment