我正在尝试构建一个简单的照片选择器,它现在有两个选项:最近和收藏夹。我正在做的是尝试通过creationDate
获取所有照片但是这会在我的数据源中以错误的顺序返回图像。多年前在数据源的开头有照片,而且不到几分钟的照片分散在各处。我认为问题在于我需要首先告诉主要的fetchResult排序顺序,但我不认为这是可能的:Unsupported sort descriptor in fetch options: (creationDate, ascending, compare:
我很感激提供任何帮助。代码:
@property (nonatomic, strong) NSMutableOrderedSet *recentsDataSource;
@property (nonatomic, strong) NSMutableOrderedSet *favoritesDataSource;
- (void)setup
{
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
for (PHAssetCollection *sub in fetchResult)
{
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc]init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *assetsInCollection = [PHAsset fetchAssetsInAssetCollection:sub options:fetchOptions];
for (PHAsset *asset in assetsInCollection)
{
[self.recentsDataSource addObject:asset];
if (asset.isFavorite)
{
[self.favoritesDataSource addObject:asset];
}
}
}
}
答案 0 :(得分:6)
我自己想出来了,这是我的解决方案:
- (void)setup
{
self.recentsDataSource = [[NSMutableOrderedSet alloc]init];
self.favoritesDataSource = [[NSMutableOrderedSet alloc]init];
PHFetchResult *assetCollection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
PHFetchResult *favoriteCollection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumFavorites options:nil];
for (PHAssetCollection *sub in assetCollection)
{
PHFetchResult *assetsInCollection = [PHAsset fetchAssetsInAssetCollection:sub options:nil];
for (PHAsset *asset in assetsInCollection)
{
[self.recentsDataSource addObject:asset];
}
}
if (self.recentsDataSource.count > 0)
{
NSArray *array = [self.recentsDataSource sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]]];
self.recentsDataSource = [[NSMutableOrderedSet alloc]initWithArray:array];
}
for (PHAssetCollection *sub in favoriteCollection)
{
PHFetchResult *assetsInCollection = [PHAsset fetchAssetsInAssetCollection:sub options:nil];
for (PHAsset *asset in assetsInCollection)
{
[self.favoritesDataSource addObject:asset];
}
}
if (self.favoritesDataSource.count > 0)
{
NSArray *array = [self.favoritesDataSource sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]]];
self.favoritesDataSource = [[NSMutableOrderedSet alloc]initWithArray:array];
}
}