如何从 PHPicker 检索 PHAsset?

0xB*_*1A8 5 ios swift phasset phpickerviewcontroller 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)
        
        
    }
Run Code Online (Sandbox Code Playgroud)

0xB*_*1A8 18

我设法在苹果论坛上从该框架的开发人员那里找到了答案:

是的,PHPickerResult 具有 assetIdentifier 属性,该属性可以包含本地标识符以从库中获取 PHAsset。要让 PHPicker 返回资产标识符,您需要使用库初始化 PHPickerConfiguration。

请注意,如果用户将您的应用置于有限照片库模式,PHPicker 不会扩展所选项目的有限照片库访问权限。这将是重新考虑应用程序是否真的需要直接访问照片库或只能处理图像和视频数据的好机会。但这真的取决于应用程序。

“认识新照片选择器”会话的相关部分从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
        }
}
Run Code Online (Sandbox Code Playgroud)

  • 还有其他人遇到 fetchResult 始终为空的问题吗?CompactMap 工作并且我得到了标识符,但是获取结果永远不会为我返回任何结果。 (2认同)
  • @JKoko 记得在 `PHPickerConfiguration` 中设置 `PHPhotoLibrary.shared()` (2认同)