5

The following code highlights the issue in 3 simple steps:

1) fetch moments

2) cache moment localIdentifier

3) fetch moment with identifier : fail( on device, iOS 8.2 )

- ( void )momentLocalIdTest
{
    PHFetchResult       * fetchResult;
    PHAssetCollection   * moment;
    NSString            * localIdentifier;

    fetchResult = [ PHAssetCollection fetchMomentsWithOptions: nil ];

    if( fetchResult.count == 0 )
        return;

    moment          = fetchResult.firstObject;
    localIdentifier = moment.localIdentifier;
    fetchResult     = [ PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers: @[ localIdentifier ] options: nil ];

    if( fetchResult.count == 0 )
        NSLog( @"AssetCollection with localIdentifier %@ not found!!!", localIdentifier );
}

Am I misunderstanding something? It seems pretty straightforward...

Any help appreciated!

Gregzo
  • 1,194
  • 7
  • 18

2 Answers2

0

I encountered the same issue as well, and could not figure out what is wrong with this code. I think this API is just plain and simply broken (8.0 through 8.4 at least)

Here's a workaround code; you basically have to respawn the PHAssetCollection instance from the identifier

PHFetchOptions *options = [PHFetchOptions new];
options.predicate = [NSPredicate predicateWithFormat:@"localIdentifier = %@", identifier];

PHAssetCollection *collection = [[PHAssetCollection fetchMomentsWithOptions:options] firstObject];
PHFetchResult *results = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
Olotiar
  • 3,225
  • 1
  • 18
  • 37
0
- (void)ph_example{
    NSError *error;
    __block NSString *sid = nil;
    NSString *title = @"foldra-moldra";

    dispatch_block_t block_1 = ^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        sid = request.placeholderForCreatedAssetCollection.localIdentifier;
    };

    dispatch_block_t block_2 = ^{
        PHFetchResult <PHAssetCollection *> *result =
        [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[sid] options:nil];
        PHAssetCollection *collection = result.firstObject;
        printf("collection: %p\r", collection);
    };

#define PH_SUCCESS_INSERT_AND_FETCH 1
#if PH_SUCCESS_INSERT_AND_FETCH
    [PHPhotoLibrary.sharedPhotoLibrary performChangesAndWait:block_1 error:&error];
    //
    // HERE: Need a flow break of -[PHPhotoLibrary performChanges:] or -[PHPhotoLibrary performChangesAndWait:]...
    // Fetch only after insert changes did applied
    // block{Create} => block{Fetch} => Found
    //
    [PHPhotoLibrary.sharedPhotoLibrary performChangesAndWait:block_2 error:&error];
#else
    // block{Create => Fetch} => Not Found
    [PHPhotoLibrary.sharedPhotoLibrary performChangesAndWait:^{
        block_1();
        block_2();
    } error:&error];
#endif
}
Roman Solodyashkin
  • 799
  • 12
  • 17