如何从 PHPicker 检索 PHAsset?

How to retrieve PHAsset from PHPicker?

WWDC20 苹果推出了 PHPicker - UIImagePickerController 的现代替代品。
我想知道是否可以使用新的照片选择器检索 PHAsset?


这是我的代码:

private func presentPicker(filter: PHPickerFilter) {
    var configuration = PHPickerConfiguration()
    configuration.filter = filter
    configuration.selectionLimit = 0
    
    let picker = PHPickerViewController(configuration: configuration)
    picker.delegate = self
    present(picker, animated: true)
}


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

我在 apple forum 上找到了这个框架的开发者的答案:

Yes, PHPickerResult has the assetIdentifier property which can contain a local identifier to fetch the PHAsset from the library. To have PHPicker return asset identifiers, you need to initialize PHPickerConfiguration with the library.

Please note that PHPicker does not extend the Limited Photos Library access for the selected items if the user put your app in Limited Photos Library mode. It would be a good opportunity to reconsider if the app really needs direct Photos Library access or can work with just the image and video data. But that really depend on the app.

The relevant section of the "Meet the new Photos picker" session begins at 10m 20s.

PhotoKit 访问的示例代码如下所示:

import UIKit
import PhotosUI
class PhotoKitPickerViewController: UIViewController, PHPickerViewControllerDelegate {
    @IBAction func presentPicker(_ sender: Any) {
            let photoLibrary = PHPhotoLibrary.shared()
            let configuration = PHPickerConfiguration(photoLibrary: photoLibrary)
            let picker = PHPickerViewController(configuration: configuration)
            picker.delegate = self
            present(picker, animated: true)
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            picker.dismiss(animated: true)
            
            let identifiers = results.compactMap(\.assetIdentifier)
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: identifiers, options: nil)
            
            // TODO: Do something with the fetch result if you have Photos Library access
    }
}