How to fetch all photos from library

為{幸葍}努か 提交于 2019-12-21 02:16:49

问题


The code shown below is what i've tried already.What I wish to achieve is to fetch all the photos from the device.Currently only a few are being fetched.How to modify the code so as to load all the images from device?

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
}

回答1:


Updated David's answer for iOS 10+ & Swift 4.x/3.x:

Request permission from the device to access photos:

Add the following value to your info.plist

Privacy - Photo Library Usage Description

And provide a string that is shown to the user.

Request all images:

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")
    }
}



回答2:


All photos is pretty easy, but you need to ensure that you're authorized first. Here's some simple code to demonstrate:

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")
    }
}

On my phone this returns 25750 items. On a fresh simulator, this should yield 5 images.



来源:https://stackoverflow.com/questions/38059953/how-to-fetch-all-photos-from-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!