-2

I want to select an image from photos using new PHPickerViewController and I want to open PHPicker directly when my controller is load.


Like this

Like this

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
         // Do any additional setup after loading the view.
         // TODO: - Here I want PhotoPicker
       }
    }
udi
  • 3,672
  • 2
  • 12
  • 33
  • 1
    Did you look at the doc? https://developer.apple.com/documentation/photokit/phpickerviewcontroller?language=objc There is even a sample code https://developer.apple.com/documentation/photokit/selecting_photos_and_videos_in_ios?language=objc Side note, when the `viewDidLoad()`, it might not be visible yet, so you can't open (ie present) the `PHPickerViewController` yet. – Larme Apr 21 '22 at 12:46

1 Answers1

9

you can call this method openPHPicker() when ever you want to place your PHPicker.

  1. You can use this code also. for opening new PHPicker.

  2. For More Knowledge about PHPicker in WWDC21 PHPicker WWDC20 Video and PHPicker WWDC21 Video

  3. WWDC PHPicker Notes PHPicker Notes


import Photos
import PhotosUI


// MARK: - PHPicker Configurations (PHPickerViewControllerDelegate)
extension ViewController: PHPickerViewControllerDelegate {
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
         picker.dismiss(animated: true, completion: .none)
         results.forEach { result in
               result.itemProvider.loadObject(ofClass: UIImage.self) { reading, error in
               guard let image = reading as? UIImage, error == nil else { return }
               DispatchQueue.main.async {
                   self.profilePictureOutlet.image = image
                   // TODO: - Here you get UIImage
               }
               result.itemProvider.loadFileRepresentation(forTypeIdentifier: "public.image") { [weak self] url, _ in
                // TODO: - Here You Get The URL
               }
          }
       }
  }

   /// call this method for `PHPicker`
   func openPHPicker() {
       var phPickerConfig = PHPickerConfiguration(photoLibrary: .shared())
       phPickerConfig.selectionLimit = 1
       phPickerConfig.filter = PHPickerFilter.any(of: [.images, .livePhotos])
       let phPickerVC = PHPickerViewController(configuration: phPickerConfig)
       phPickerVC.delegate = self
       present(phPickerVC, animated: true)
   }
}
Chandan
  • 283
  • 2
  • 6