iOS 8 で導入された新しいPhotos
フレームワークでは、以下を使用できます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;
}];
これにはスマート アルバムは含まれません (そして、私の経験では、有効な「推定カウント」がありません)。代わりに、アセットを取得して実際のカウントを取得できます。
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;
}];
ところで、ライブラリの承認をまだ要求していない場合は、要求する必要があります。たとえば、次のようにします。
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
// insert your image counting logic here
}
}];
古いAssetsLibrary
フレームワークでは、次のことができます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