klaus zhang
klaus zhang

Reputation: 71

Sometimes PHAsset fetchAssetsWithLocalIdentifiers:options method return a empty fetch result

Has anyone encountered this problem? Any advice will be appreciated.

Code as below: Sometimes the resultAsset is empty. Maybe happened on iOS9.3 occasionally.

- (PHAsset*)retrievePHAssetFromLocalIdentifier:(NSString*)localIdentifier {
    if (!localIdentifier) {
        return nil;
    }
    NSArray *localIdentifiers = @[localIdentifier];
    PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:localIdentifiers options:nil];
    PHAsset *resultAsset = [result firstObject]; //Sometimes the resultAsset is empty. Maybe happened on iOS9.3 occasionally.
    if (!resultAsset) {
        NSLog(@"can't retrieve PHAsset from localIdentifier:%@",localIdentifier);
    }
    return resultAsset;
}

Upvotes: 2

Views: 1656

Answers (1)

klaus zhang
klaus zhang

Reputation: 71

This issue happened when choosing photos from "my photo stream". Finally, I got this workaround to solve it. I hope it helps you.

-(PHAsset*)workAroundWhenAssetNotFound:(NSString*)localIdentifier{

    __block PHAsset *result = nil;
    PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
    userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumMyPhotoStream options:userAlbumsOptions];

    if(!userAlbums || [userAlbums count] <= 0) {            
        return nil;
    }

    [userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx1, BOOL *stop) {
        PHFetchOptions *fetchOptions = [PHFetchOptions new];
        fetchOptions.predicate = [NSPredicate predicateWithFormat:@"self.localIdentifier CONTAINS %@",localIdentifier];
        PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];

        [assetsFetchResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop1) {
            if(asset){
                result = asset;
                *stop1 = YES;
                *stop = YES;
            }
        }];
    }];
    return result;
}

Reference link:How to get photo from My Photo Stream Album

Upvotes: 2

Related Questions