How do I use Photo Picker and PHPickerViewController in Swift?

The Photo Picker and PHPickerViewController allow developers to easily integrate photo selection functionality into their iOS applications. This is beneficial for apps that require the user to select images or videos, as it provides a user-friendly interface while maintaining privacy by not giving direct access to the user's photo library.

Using PHPickerViewController

To implement the PHPickerViewController in your Swift application, follow these steps:

import UIKit import PhotosUI class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func selectPhoto(_ sender: UIButton) { var config = PHPickerConfiguration() config.selectionLimit = 1 // allows selecting only one photo config.filter = .images // allows only images to be selected let picker = PHPickerViewController(configuration: config) picker.delegate = self present(picker, animated: true, completion: nil) } } extension ViewController: PHPickerViewControllerDelegate { func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { picker.dismiss(animated: true, completion: nil) guard let result = results.first else { return } result.itemProvider.loadObject(ofClass: UIImage.self) { (object, error) in if let image = object as? UIImage { // Use the selected image } } } }

This code sets up a simple interface where pressing a button presents the photo picker. The selected image is then loaded using the `loadObject` method.


PHPickerViewController Photo Picker Swift iOS development image selection