借助 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