首页 > 解决方案 > 如何在 iOS 14 上仅获取具有授予访问权限的资产?

问题描述

以前在我们的项目中,我们曾经PHAsset.fetchAssets(with:)获取用户库中所有媒体的列表(返回为PHFetchResult<PHAsset>)。我们打电话object(at:)来访问个别项目,效果很好。

借助 iOS 14 及其新的隐私功能,用户可以选择允许仅访问其图库中选定的照片。问题是它PHAsset.fetchAssets(with:)仍然返回用户拥有的所有资产,但只有应用程序有权访问的资产才能用于检索实际的照片或视频。在这种情况下, 的count属性PHFetchResult也不是所需要的。

有什么方法可以方便地仅请求具有授予访问权限的媒体项目,以便我立即拥有适当的计数和资产?

到目前为止,我发现的唯一示例是枚举资产并为每个资产请求相应的图像,然后手动过滤掉无法访问的资产。

let assets = PHAsset.fetchAssets(with: fetchOptions)
print(assets.count) // prints 6 and equals all items in photo library
        
var assetsWithGrantedAccess: [UIImage] = []
        
let filteredImagesQueue = DispatchQueue(label: "filter.images.queue")
let dispatchGroup = DispatchGroup()
        
assets.enumerateObjects { (asset, _, _) in
     dispatchGroup.enter()
     PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: imageRequestOptions) { (image, _) in
          defer { dispatchGroup.leave() }
          guard let image = image else {
               return
          }
          filteredImagesQueue.async {
               assetsWithGrantedAccess.append(image)
          }
     }
}
        
dispatchGroup.notify(queue: filteredImagesQueue) {
     print(assetsWithGrantedAccess.count) // prints 2 and equals number of items with granted access
}

标签: iosobjective-cswiftios14

解决方案


这似乎仅在模拟器中发生, PHAsset.fetchAssets(with:)在设备上仅返回具有授予访问权限的媒体项。


推荐阅读