Ahmed Abed Ahmed Abed - 6 months ago 86x
Swift Question

List all photo albums in iOS

I need to get all photo albums in iPhone.

I know I can start image picker to let user selects image from it. But I need to develop my own image browser.

All the code I found work with image picker or they already know album name.

I need first to list all photo albums names then user will select one of them, then I will display images in this album.

All these steps will done in customized layouts.

Can I list all photo albums?


I use this to get just a few albums but you can get more:

private func setupPhotos() {
        let fetchOptions = PHFetchOptions()

    let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: fetchOptions)

    let topLevelfetchOptions = PHFetchOptions()

    let topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollectionsWithOptions(topLevelfetchOptions)

    let allAlbums = [topLevelUserCollections, smartAlbums]

    for i in 0 ..< allAlbums.count {
        let result = allAlbums[i]

        result.enumerateObjectsUsingBlock { (asset, index, stop) -> Void in
            if let a = asset as? PHAssetCollection {
                let opts = PHFetchOptions()

                if #available(iOS 9.0, *) {
                    opts.fetchLimit = 1

                let ass = PHAsset.fetchAssetsInAssetCollection(a, options: opts)
                if let _ = ass.firstObject {
                    let obj = MYSpecialAssetContainerStruct(asset: a)

            if i == (allAlbums.count - 1) && index == (result.count - 1) {
                self.data.sortInPlace({ (a, b) -> Bool in
                    return a.asset.localizedTitle < b.asset.localizedTitle

EDIT: This will get you the PHAssetCollections of the albums, then I put them in cells which have this method for getting the latest image thumbnail from the album.

private func downloadAndSetImage(asset: MYSpecialAssetContainerStruct) {
    if asset.thumbnail == nil {
        let imageRequestOptions = PHImageRequestOptions()
        imageRequestOptions.networkAccessAllowed = false
        imageRequestOptions.synchronous = true
        imageRequestOptions.deliveryMode = .HighQualityFormat

            targetSize: self.targetImageSize(),
            contentMode: .AspectFit,
            options: imageRequestOptions,
            resultHandler: { (img, info) -> Void in
                asset.thumbnail = img
                self.albumImage.image = asset.thumbnail
    } else {
        albumImage.image = asset.thumbnail