Reputation: 346
I need get all photo albums from device. I use this code for fetch albums:
func fetchAlbums() {
// Get all user albums
let userAlbumsOptions = PHFetchOptions()
userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
let userAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.any, options: userAlbumsOptions)
userAlbums.enumerateObjects( {
if let collection = $0.0 as? PHAssetCollection {
print("album title: \(collection.localizedTitle)")
let onlyImagesOptions = PHFetchOptions()
onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.image.rawValue)
if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions) {
print("Images count: \(result.count)")
if result.count > 0 {
//Add album titie
self.albumsTitles.append(collection.localizedTitle!)
//Add album
self.albumsArray.append(result as! PHFetchResult<AnyObject>)
}
}
}
} )
}
But i can't get all photos. All albums without photos from iCloud library, only local photos. I use Collection View for preview photo. Example my code for fetch photos from selected album:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: AlbumPhotoCollectionViewCell.self),
for: indexPath as IndexPath) as! AlbumPhotoCollectionViewCell
//Array with albums
let asset = self.albumsArray[indexSelectedAlbum]
let album = asset[indexPath.item]
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(for: album as! PHAsset ,
targetSize: self.assetThumbnailSize,
contentMode: .aspectFill,
options: options,
resultHandler: {(result, info)in
if result != nil {
cell.albumPhoto.image = result
}
})
return cell
}
Upvotes: 0
Views: 2743
Reputation: 346
I change fetch and all working.
Old code:
if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions){
//Code
}
New code
let result = PHAsset.fetchAssets(in: collection, options: onlyImagesOptions)
Upvotes: 1