PHPickerViewController 有很多好处,不需要照片权限,体验和系统相册一致,比如支持搜索,性能更好,是独立的进程处理,app想截图都不行,完美的隐私保护。但是也有很多不便,很好用的PHAsset就用不到了。导致不能得到视频地址,需要把视频拷贝到app中。发现 PHPickerResult 有个 assetIdentifier 字段,像能转化为PHAsset,苹果提供了一段代码,如下:
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
}
}
这段代码得到 assetIdentifier,然后得到 PHAsset,这样就能愉快的玩耍了吗,那是不可能的,有两个坑
- 一是创建PHPickerViewController的时候配置需要传PHPhotoLibrary,要不然会得不到assetIdentifier
- 二是拿到了assetIdentifier,还是拿不到PHAsset,因为还需要照片库的权限。