有时PHAsset fetchAssetsWithLocalIdentifiers:options方法返回一个空的获取结果

时间:2017-03-17 02:37:33

标签: fetch phasset

有没有人遇到过这个问题?任何建议将不胜感激。

代码如下: 有时resultAsset为空。也许偶尔会发生在iOS9.3上。

- (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;
}

1 个答案:

答案 0 :(得分:1)

从"我的照片流"中选择照片时发生此问题。最后,我得到了解决方法。我希望它可以帮助你。

-(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;
}

参考链接:How to get photo from My Photo Stream Album