【问题标题】:How to fetch all photos from library如何从库中获取所有照片
【发布时间】:2016-10-29 19:42:48
【问题描述】:

下面显示的代码是我已经尝试过的。我希望实现的是从设备中获取所有照片。目前只获取少数几个。如何修改代码以加载所有图像来自设备?

let fetchOptions = PHFetchOptions()

let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Moment, subtype: .Any, options: fetchOptions)

if let first_Obj:AnyObject = collection.firstObject
{
    self.assetCollection = first_Obj as! PHAssetCollection
}

【问题讨论】:

  • 您只查看结果中的第一个值。为什么不查看结果中的所有值?你检查过count吗?
  • 当您似乎对资产感兴趣时,您也在获取集合。
  • 如何获取所有值??抱歉,我是新手

标签: ios swift photos


【解决方案1】:

更新了 David 对 iOS 10+ 和 Swift 4.x/3.x 的回答:

向设备请求访问照片的权限:

将以下值添加到您的info.plist

隐私 - 照片库使用说明

并提供一个向用户显示的字符串。

请求所有图片:

PHPhotoLibrary.requestAuthorization { status in
    switch status {
    case .authorized:
        let fetchOptions = PHFetchOptions()
        let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        print("Found \(allPhotos.count) assets")
    case .denied, .restricted:
        print("Not allowed")
    case .notDetermined:
        // Should not see this when requesting
        print("Not determined yet")
    }
}

【讨论】:

  • 这可行,但如果你不将“隐私 - 照片库使用说明”添加到 info.plist,它会崩溃
  • @MrStanev 实际上在“请求设备访问照片的许可”下的答案顶部注明了
  • @CodeBender 是否可以限制获取?可以分页吗?
  • @Dipang 是的,您可以使用 sortDescriptors、fetchLimits 和谓词的组合来获得您想要的。
【解决方案2】:

所有照片都很容易,但您需要先确保您已获得授权。下面是一些简单的代码来演示:

PHPhotoLibrary.requestAuthorization { (status) in
    switch status
    {
    case .Authorized:
        print("Good to proceed")
        let fetchOptions = PHFetchOptions()
        let allPhotos = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
        print("Found \(allPhotos.count) images")
    case .Denied, .Restricted:
        print("Not allowed")
    case .NotDetermined:
        print("Not determined yet")
    }
}

在我的手机上,这将返回 25750 个项目。在新的模拟器上,这应该会产生 5 张图像。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多