【问题标题】:PHAsset, how to retrieve the specific PHAsset object after app restarts (ios8 Photos)PHAsset,如何在应用重启后检索特定的 PHAsset 对象(ios8 Photos)
【发布时间】:2016-02-23 07:12:54
【问题描述】:

我曾经使用ALAssetLibrary。并且它有assetForURL功能,所以我可以将URL保存到NSUserDefaults,并在应用重启后通过URL检索ALasset

但是,当我更改为PHAsset 时,我找不到这种功能。我找到的是fetchAssetsWithALAssetURLs,但是ALasset会弃用它,所以我不倾向于使用这个功能。 (保存 ALAsset url,并从 fetchAssetsWithALAssetURLs 检索 PHAsset)

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

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

【问题讨论】:

    标签: ios iphone photos alassetslibrary phasset


    【解决方案1】:

    关键是属性.localIdentifier。它是“晦涩的”,因为它实际上是超类PHObject 的属性。文档是这样说的:

    永久标识对象的唯一字符串。 (只读)

    声明

    斯威夫特

    var localIdentifier: String { get }

    讨论

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

    【讨论】:

      【解决方案2】:

      您不需要在 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;
                }
            }];
         }
       }];
      

      【讨论】:

      • 是的,它可以实现我的目标,但枚举所有照片需要很多时间... fetchAssetsWithLocalIdentifiers:options 更好。 (谢谢,Grimxn)
      猜你喜欢
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2014-12-20
      • 2018-02-08
      相关资源
      最近更新 更多