如何从库中获取所有照片

时间:2016-06-27 17:35:12

标签: ios swift photos

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

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
}

2 个答案:

答案 0 :(得分:17)

更新了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")
    }
}

答案 1 :(得分:0)

所有照片都非常简单,但您需要确保首先获得授权。这是一些简单的代码来演示:

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张图像。