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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容