I use this to get just a few albums but you can get more:
private func setupPhotos() {
let fetchOptions = PHFetchOptions()
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
let topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollections(with: fetchOptions)
let allAlbums = [topLevelUserCollections, smartAlbums]
allAlbums.enumerateObjects {(assetCollection, index, stop) in
if #available(iOS 9.0, *) {
fetchOptions.fetchLimit = 1
}
let assets = PHAsset.fetchAssets(in: assetCollection, options: fetchOptions)
if let _ = assets.firstObject {
let assetObject = MYSpecialAssetContainerStruct(asset: assets)
self.myDataArray.append(assetObject)
}
}
self.myDataArray.sortInPlace {(a, b) in
return a.asset.localizedTitle < b.asset.localizedTitle
}
tableView.reloadData()
}
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) {
guard asset.thumbnail == nil else {
albumImage.image = asset.thumbnail
return
}
let imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.isNetworkAccessAllowed = false
imageRequestOptions.isSynchronous = true
imageRequestOptions.deliveryMode = .highQualityFormat
PHImageManager.default().requestImage(
for: asset.asset,
targetSize: CGSize(width: 200, height: 200),
contentMode: .aspectFit,
options: imageRequestOptions,
resultHandler: {(img, info) in
asset.thumbnail = img
self.albumImage.image = asset.thumbnail
}
)
}