With the new Photos
framework, introduced in iOS 8, you can use estimatedAssetCount
:
NSUInteger __block estimatedCount = 0;
PHFetchResult <PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
[collections enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
estimatedCount += collection.estimatedAssetCount;
}];
That won't include the smart albums (and, in my experience, they don't have valid "estimated counts"), so you can alternatively fetch the assets to get the actual count:
NSUInteger __block count = 0;
// Get smart albums (e.g. "Camera Roll", "Recently Deleted", "Panoramas", "Screenshots", etc.
PHFetchResult <PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[collections enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
PHFetchResult <PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
count += assets.count;
}];
// Get the standard albums (e.g. those from iTunes, created by apps, etc.), too
collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
[collections enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
PHFetchResult <PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
count += assets.count;
}];
And, by the way, if you haven't already requested authorization for the library, you should do so, e.g.:
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
// insert your image counting logic here
}
}];
With the old AssetsLibrary
framework, you can enumerateGroupsWithTypes
:
NSUInteger __block count = 0;
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (!group) {
// asynchronous counting is done; examine `count` here
} else {
count += group.numberOfAssets;
}
} failureBlock:^(NSError *err) {
NSLog(@"err=%@", err);
}];
// but don't use `count` here, as the above runs asynchronously