PHPicker for iOS 14 踩坑记录

适配的参考资料

旧版的 UIImagePicker 返回的是 PHAsset
但是新版的返回的是一个新的类 PHPickerResult

如果我们要获取 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
        }
}
let photoLibrary = PHPhotoLibrary.shared()
let configuration = PHPickerConfiguration(photoLibrary: photoLibrary)

遇到的问题

这样初始化之后,选择图片时,依然会弹出让你选择可访问的图片范围。那么问题来了:

  • 假设相册中有 ABC 三张图,我只授权了 AB 两张有权限
  • 这时候唤起 PHPicker,能看到所有的图。此时去选择 C 图片,可以拿到 PHAsset 的 assetIdentifier,但是通过 PHAsset.fetchAssets 去获取 PHAsset 则会失败

苹果论坛的解释:

参考链接

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.

简而言之,这种情况下,我们始终只能拿到 UIImage,拿不到 PHAsset

你可能感兴趣的:(PHPicker for iOS 14 踩坑记录)