【发布时间】:2017-08-18 00:58:42
【问题描述】:
我使用YangMingShan 作为照片选择器,这正是我需要的,但是当用户有很多照片时我遇到了问题。
我已经在一部包含 25,000 多张照片和 250 个相册的手机上进行了测试,当我展示视图控制器时,应用会在 collectionView 加载之前冻结大约 30 秒。
这是有问题的代码,我正在尝试找出是否有更优化的方法来获取结果。
- (void)fetchCollections
{
NSMutableArray *allAblums = [NSMutableArray array];
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
__block __weak void (^weakFetchAlbums)(PHFetchResult *collections);
void (^fetchAlbums)(PHFetchResult *collections);
weakFetchAlbums = fetchAlbums = ^void(PHFetchResult *collections) {
// create fecth options
PHFetchOptions *options = [PHFetchOptions new];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
for (PHCollection *collection in collections) {
if ([collection isKindOfClass:[PHAssetCollection class]]) {
PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];
if (assetsFetchResult.count > 0) {
[allAblums addObject:@{@"collection": assetCollection
, @"assets": assetsFetchResult}];
}
}
else if ([collection isKindOfClass:[PHCollectionList class]]) {
// If there are more sub-folders, dig into the collection to fetch the albums
PHCollectionList *collectionList = (PHCollectionList *)collection;
PHFetchResult *fetchResult = [PHCollectionList fetchCollectionsInCollectionList:(PHCollectionList *)collectionList options:nil];
weakFetchAlbums(fetchResult);
}
}
};
PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
fetchAlbums(topLevelUserCollections);
for (PHAssetCollection *collection in smartAlbums) {
PHFetchOptions *options = [PHFetchOptions new];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:options];
if (assetsFetchResult.count > 0) {
// put the "all photos" in the first index
if (collection.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary) {
[allAblums insertObject:@{@"collection": collection
, @"assets": assetsFetchResult} atIndex:0];
}
else {
[allAblums addObject:@{@"collection": collection
, @"assets": assetsFetchResult}];
}
}
}
self.collectionItems = [allAblums copy];
}
【问题讨论】:
标签: ios objective-c