Sobes.tech
Junior

How to get an image from the gallery?

sobes.tech AI

Answer from AI

To obtain an image from the gallery in iOS, UIImagePickerController is used.

Key steps:

  1. Create an instance of UIImagePickerController.
  2. Set the sourceType of the controller to .photoLibrary.
  3. Assign a delegate for UIImagePickerController. The delegate must conform to the UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols.
  4. Present the UIImagePickerController.
  5. In the delegate method imagePickerController(_:didFinishPickingMediaWithInfo:), handle the selected image.

Example implementation:

import UIKit
import PhotosUI // For PHPickerViewController in iOS 14+

class YourViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    // MARK: - Open Photo Library (Traditional)

    func openPhotoLibraryTraditional() {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false // Set to true if editing is needed
            self.present(imagePicker, animated: true, completion: nil)
        } else {
            // Handle case where photo library is not available
            print("Photo Library not available")
        }
    }

    // MARK: - Open Photo Library (Modern - iOS 14+)

    @available(iOS 14, *)
    func openPhotoLibraryModern() {
        var config = PHPickerConfiguration()
        config.filter = .images // Filter for selecting only images
        config.selectionLimit = 1 // Set the number of items to select
        let picker = PHPickerViewController(configuration: config)
        picker.delegate = self // Delegate for PHPickerViewController
        self.present(picker, animated: true, completion: nil)
    }

    // MARK: - UIImagePickerControllerDelegate Methods

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let pickedImage = info[.originalImage] as? UIImage {
            // Here you can use the selected image (pickedImage)
            print("Image selected: \(pickedImage.size)")
            // For example, assign it to a UIImageView or save it
            // self.imageView.image = pickedImage
        }
        picker.dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

    // MARK: - PHPickerViewControllerDelegate (iOS 14+)

    @available(iOS 14, *)
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true) // Close picker regardless of selection

        guard !results.isEmpty else {
            return // Nothing selected
        }

        let itemProvider = results[0].itemProvider // Handle the first selected item (if selectionLimit = 1)

        if itemProvider.canLoadObject(ofClass: UIImage.self) {
            itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in
                if let error = error {
                    print("Error loading image: \(error.localizedDescription)")
                    return
                }
                if let selectedImage = image as? UIImage {
                    DispatchQueue.main.async {
                        // Here you can use the selected image (selectedImage)
                        print("Modern picker image selected: \(selectedImage.size)")
                        // self.imageView.image = selectedImage
                    }
                }
            }
        }
    }
}

Using PHPickerViewController (available from iOS 14) is a more modern and preferred way, as it provides greater control over user privacy and selection.

Don't forget to add a description of the photo library usage in your app's Info.plist file:

<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to your photo library to select images.</string>

(for UIImagePickerController)

<!-- PHPickerViewController does not require a separate access key to the library -->