PHAsset,如何在应用程序重新启动后检索特定的PHAsset对象(iOS8照片)

3

我曾经使用过ALAssetLibrary,它有assetForURL功能,因此我可以将URL保存到NSUserDefaults中,并在应用程序重新启动后通过URL检索ALasset

然而,当我切换到PHAsset时,我找不到这种类型的功能。我找到的是fetchAssetsWithALAssetURLs,但它将被淘汰用于ALasset,所以我不想使用这个函数(保存ALAsset url,并从fetchAssetsWithALAssetURLs检索PHAsset)。

我认为将整个PHAsset对象保存到键“localIdentifier”的NSUserDefaults中是唯一的方法,因此我可以在应用程序重新启动后重新加载它。检索phasset对象的方法是通过关键字localIdentifier。

这是实现我的目标的好方法吗?还有其他方法吗?

2个回答

11
关键在于属性.localIdentifier,这实际上是超类PHObject的一个属性,因此比较"晦涩"。文档中如下所述:

唯一字符串,持久地标识对象。(只读)

声明

SWIFT

var localIdentifier: String { get }

讨论

使用此字符串通过fetchAssetsWithLocalIdentifiers:options:fetchAssetCollectionsWithLocalIdentifiers:options:, 或 fetchCollectionListsWithLocalIdentifiers:options:方法查找对象。


5
您不需要在NSUserDefaults中设置整个PHAsset对象。 只需在NSUserDefaults中为任何键(如"photoIdentifier")设置localIdentifier即可。
假设您有一个PHAsset对象, 请使用以下方法保存localIdentifier。
PHAsset *assetObject;

[[NSUserDefaults standardUserDefaults] setObject:assetObject.localIdentifier forKey:@"PhotoIdentifier"];

现在,要检索该资产,您需要遍历照片集合并通过其标识符获取确切的照片,如下所示。
PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];

[allPhotos enumerateObjectsUsingBlock:^(PHAsset   * _Nonnull photoAsset, NSUInteger idx, BOOL * _Nonnull stop) {

 NSString *photoIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:@"PhotoIdentifier"];
 if([photoIdentifier isEqualToString:photoAsset.localIdentifier]){

     // asset here

    // if you want Image then get UIImage from PHAsset as follows.           

     [[PHImageManager defaultManager]requestImageForAsset:photoAsset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage *result, NSDictionary *info){
          if ([info objectForKey:PHImageErrorKey] == nil && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue]) {

             // image is here as a result parameter
             *stop = YES;
          }
      }];
   }
 }];

7
可以实现我的目标,但是列举所有照片需要很长时间……使用fetchAssetsWithLocalIdentifiers:options更好。(感谢,Grimxn) - Bruce Tsai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接