5

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)
        
        
    }
4

1 回答 1

21

我设法在苹果论坛上从这个框架的开发者那里找到了答案:

是的,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
        }
}
于 2020-06-28T17:11:59.133 回答