Question

How can I get the image name using Swift PhotoPicker?

Answer and Explanation

Retrieving the image name using Swift's `PhotoPicker` can be a bit indirect, as `PhotoPicker` primarily provides access to image data rather than file paths. Here’s how you can achieve this by accessing the underlying asset and its metadata:

1. Import Necessary Frameworks:

- First, make sure you import the required frameworks: `PhotosUI` and `Photos`.

import PhotosUI
import Photos

2. Implement `PHPickerViewControllerDelegate`:

- Conform your view controller or designated class to `PHPickerViewControllerDelegate` to handle the selected images.

3. Present the PhotoPicker:

- Here’s a simplified example of how to present the photo picker:

var picker = PHPickerViewController(configuration: config)
picker.delegate = self
present(picker, animated: true)

4. Extract Image Name in `picker(_:didFinishPicking:)`:

- Inside the `picker(_:didFinishPicking:)` delegate method, you'll need to access the underlying `PHAsset` of the selected item to obtain the original file name.

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
  picker.dismiss(animated: true)

  guard let provider = results.first?.itemProvider else { return }

  if provider.canLoadObject(ofClass: UIImage.self) {
    provider.loadObject(ofClass: UIImage.self) { image, _ in
       guard let image = image as? UIImage else { return }
       if let assetIdentifier = results.first?.assetIdentifier{
         let assets = PHAsset.fetchAssets(withLocalIdentifiers: [assetIdentifier], options: nil)
         if let asset = assets.firstObject {
            let assetResources = PHAssetResource.assetResources(for: asset)
            let originalFilename = assetResources.first?.originalFilename ?? "unknown" //original filename
           print("Original image name: \(originalFilename)")
         }
      }
    }
  }
}

5. Handling Errors:

- Ensure you handle cases where the `assetIdentifier` is not available or no `PHAssetResource` is found. The example above provides default values if an original file name is not obtainable.

Additional Notes:

- The provided `originalFilename` is the name of the image when it was first saved to the Photo Library. It may have been modified by the user.

- Make sure you are handling photo library access permissions correctly in your application.

This approach allows you to retrieve the name of the image selected using `PhotoPicker` by working with `PHAsset` and `PHAssetResource` provided by the `Photos` framework.

More questions