使用Photos Framework使用本地标识符获取相册

时间:2015-02-09 17:37:14

标签: ios photosframework

我正在跟踪用户选择了哪张相册并将其作为字符串(albumName)传递给下一位VC。

我想仅获取该相册中的照片以供进一步选择和处理。

这是我认为可以解决的问题,但我必须遗漏一些东西:

-(void) fetchImages{
    self.assets = [[PHFetchResult alloc]init];
        NSLog(@"Album Name:%@",self.albumName);

    if (self.fromAlbum) {


        PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[self.albumName]    options:nil];
        PHAssetCollection *collection = userAlbums[0];

        PHFetchOptions *onlyImagesOptions = [PHFetchOptions new];
        onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];

        NSLog(@"Collection:%@", collection.localIdentifier);

        self.assets = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions];

.....

当我记录collection.localIdentifier时我得到null所以没有提取任何收藏/专辑。

我错过了什么/弄乱了什么?

由于

2 个答案:

答案 0 :(得分:2)

如果您尝试按专辑名称提取集合,请使用以下代码

    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", albumNamed];
    PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
                                                           subtype:PHAssetCollectionSubtypeAny
                                                           options:fetchOptions];

PHAssetCollection * collection = fetchResult.firstObject;

答案 1 :(得分:1)

相册名称不是本地标识符,这是方法fetchAssetCollectionsWithLocalIdentifiers返回nil的原因。 此外,相册的名称也不是唯一的,并且可以创建多个具有相同名称的相册,因此在这种情况下,您的应用可能无法正常工作。
我猜你之前已经获得了资产收藏并保留了它的资产。字符串localizedTitle中的albumName 我建议您保留并使用localIdentifier assetreglection而不是localizedTitle并将其传递给VC。然后,您将能够使用该标识符轻松获取资产。

 //Assume we have previously done this to fetch album name and identifier
 PHFetchResult * myFirstFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
 PHAssetCollection * myFirstAssetCollection = myFirstFetchResult.firstObject;
 NSString * albumName = myFirstAssetCollection.localizedTitle;
 NSString * albumIdentifier = myFirstAssetCollection.localIdentifier;    //<-Add this...

 //Pass albumIdentifier to VC...

 //Inside your 'fetchImages' method use this to get assetcollection from passed albumIdentifier
 PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[self.albumIdentifier] options:nil];
 PHAssetCollection *collection = userAlbums.firstObject;
 //Now you have successfully passed and got asset collection and you can use
相关问题