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

Bru*_*sai 3 iphone photos ios alassetslibrary phasset

我以前用过ALAssetLibrary.并且它具有assetForURL功能,因此我可以在应用程序重新启动后将URL保存到URL NSUserDefaultsALasset通过URL 检索.

但是,当我换到时PHAsset,我找不到这种功能.我发现的是fetchAssetsWithALAssetURLs,但它会被弃用ALasset,所以我不倾向于使用这个功能.(保存ALAsset网址,并从中检索PHAsset fetchAssetsWithALAssetURLs)

我认为这是将整个PHAsset对象保存到NSUserDefaults关键"localIdentifier" 的唯一方法,所以我可以在应用程序重启后重新加载它.要通过key localIdentifier检索phasset对象.

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

Gri*_*mxn 10

关键是财产.localIdentifier.这是"模糊",因为它实际上是超级阶级的财产PHObject.以下是文档所说的内容:

一个持久标识对象的唯一字符串.(只读)

宣言

迅速

var localIdentifier: String { get }

讨论

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


rus*_*ani 5

您无需在NSUserDefaults中设置整个PHAsset对象. 只需在NSUserDefaults中为任何键设置localIdentifier,例如"photoIdentifier".

那么假设你有一个PHAsset对象

使用下面保存localIdentifier.

PHAsset *assetObject;

[[NSUserDefaults standardUserDefaults] setObject:assetObject.localIdentifier forKey:@"PhotoIdentifier"];
Run Code Online (Sandbox Code Playgroud)

现在要检索该资产,您需要迭代照片集合并通过其标识符获取完整的照片.

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;
          }
      }];
   }
 }];
Run Code Online (Sandbox Code Playgroud)

  • 是的,它可以实现我的目标,但枚举所有照片需要花费大量时间... fetchAssetsWithLocalIdentifiers:选项更好.(谢谢,Grimxn) (7认同)