簡體   English   中英

使用Photos Framework使用本地標識符獲取相冊

[英]Fetch Album with local Identifier using Photos Framework

我正在跟蹤用戶選擇了哪張相冊並將其作為字符串(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所以沒有提取集合/專輯。

我錯過了什么/弄亂了什么?

謝謝

如果您嘗試按專輯名稱提取集合,請使用以下代碼

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

PHAssetCollection * collection = fetchResult.firstObject;

專輯名稱不是本地標識符,這就是方法fetchAssetCollectionsWithLocalIdentifiers返回nil的原因。
此外,相冊的名稱也不是唯一的,並且可以創建多個具有相同名稱的相冊,因此在這種情況下,您的應用可能無法正常工作。
我猜你之前已經獲取了資產集合,並將其“ localizedTitle ”保留在字符串albumName
我建議你保留並使用localIdentifier的localIdentifier而不是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM