How to write native photo picker

Asked on 2024-08-03

1 search

To write a native photo picker, you can use the PhotoKit framework provided by Apple. Here are the steps to implement a photo picker in your app:

  1. Import the PhotoKit framework:

    import PhotosUI
    
  2. Create a PHPickerViewController:

    var configuration = PHPickerConfiguration()
    configuration.selectionLimit = 1 // Set the limit to the number of photos you want to pick
    let picker = PHPickerViewController(configuration: configuration)
    picker.delegate = self
    
  3. Present the picker:

    present(picker, animated: true, completion: nil)
    
  4. Implement the delegate method to handle the selected photos:

    extension YourViewController: PHPickerViewControllerDelegate {
        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            picker.dismiss(animated: true, completion: nil)
            for result in results {
                result.itemProvider.loadObject(ofClass: UIImage.self) { (object, error) in
                    if let image = object as? UIImage {
                        DispatchQueue.main.async {
                            // Use the selected image
                            self.imageView.image = image
                        }
                    }
                }
            }
        }
    }
    

For more detailed information on working with PhotoKit, you can refer to the session Build a great Lock Screen camera capture experience from WWDC 2024. This session covers various aspects of capturing and handling photos and videos, including permissions and best practices.

How to write native photo picker | Ask WWDC