6

我試圖建立一個簡單的照片選擇器,現在有兩個選項:最近和最愛。我在做的是試圖通過creationDate獲取所有照片,但是這是在我的數據源中以錯誤的順序返回圖像。在數據源的開頭有幾年前的照片,不到幾分鐘的照片散佈在整個數據源中。我認爲問題是我需要首先告訴主要的fetchResult排序順序,但我認爲這是不可能的:Unsupported sort descriptor in fetch options: (creationDate, ascending, compare:PHFetchResult獲取所有照片並按日期排序不一致

我希望提供任何幫助。代碼:

@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]; 
      } 
     } 
    } 
} 

回答

5

我想通了這一點我自己,這是我的解決方案:

- (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]; 
    } 
} 
+0

PHFetchResult不符合協議順序,因此我們不能內部使用它。在聲明。 – saiday