有时 PHAsset fetchAssetsWithLocalIdentifiers:options 方法会返回一个空的



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

代码如下:有时结果资产为空。也许偶尔发生在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;
}

从"我的照片流"中选择照片时,会发生此问题。最后,我得到了这个解决方法来解决它。我希望它对你有所帮助。

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

参考链接:如何从我的照片流相册中获取照片

最新更新