从UIImagePickerController获取PHAsset

时间:2018-09-07 17:28:49

标签: ios objective-c uiimagepickercontroller phasset

我正在尝试从UIImagePickerController获取PHAsset并使用以下代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

     //   NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
        PHAsset *phAsset = [info valueForKey:UIImagePickerControllerPHAsset];
        if (phAsset) {
            [assetsArr addObject:phAsset];
            [galleryArr addObject:[info valueForKey:UIImagePickerControllerOriginalImage]];
        }

        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [self.galleryCollectionView reloadData];
            [picker dismissViewControllerAnimated:YES completion:nil];
        });
    });


}

如果源类型为UIImagePickerControllerSourceTypePhotoLibrary,则可以通过上述代码获取PHAsset。但是,如果源类型为UIImagePickerControllerSourceTypeCamera,则PHAsset为nil。

在这种情况下如何获得PHAsset?

2 个答案:

答案 0 :(得分:0)

如果UIImagePickerControllerReferenceURL具有某些值,则可以使用以下代码获取资产:

PHFetchResult<PHAsset *> *result = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:imageURL] options:nil];

根据您的要求,它可能有多个资产可供选择。

答案 1 :(得分:0)

如果是拍照得到的图片,可以通过Info Dictionary获取原图

然后将图片保存在相册中

并获取 PHAsset 对象。

代码如下:

  /// Save image to album.
  static func saveImageToAlbum(image: UIImage, completion: ( (Bool, PHAsset?) -> Void )? ) {
  let status = PHPhotoLibrary.authorizationStatus()
  
  if status == .denied || status == .restricted {
      completion?(false, nil)
      return
  }
  
  var placeholderAsset: PHObjectPlaceholder? = nil
  PHPhotoLibrary.shared().performChanges({
      let newAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
      placeholderAsset = newAssetRequest.placeholderForCreatedAsset
  }) { (suc, error) in
      DispatchQueue.main.async {
          if suc {
              let asset = self.getAsset(from: placeholderAsset?.localIdentifier)
              completion?(suc, asset)
          } else {
              completion?(false, nil)
          }
      }
  }
}

  private static func getAsset(from localIdentifier: String?) -> PHAsset? {
  guard let id = localIdentifier else {
      return nil
  }
  let result = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil)
  if result.count > 0{
      return result[0]
  }
  return nil

}