如何使用 Swift 通过 PHAsset 访问 UIImage 的元数据

How to get access to metadata for UIImage via PHAsset using Swift

我正在尝试获取此工作代码,该代码通过 ImagePicker 中的 selectedImage 检索 UIImage 并通过 savePhoto 方法保存它,同时获取 UImage 的元数据:

原码:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){

    if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

    //Successfully got the image, now upload it

        //Get a reference to the camera view controller and call the savePhoto method
        let cameraVC = self.selectedViewController as? CameraViewController

        if let cameraVC = cameraVC {
            cameraVC.savePhoto(image: selectedImage)
        }

//Dismiss the picker
picker.dismiss(animated: true, completion: nil)
}
}

这是我尝试过的,但是 thisAsset 总是返回 nil,所以它基本上跳过了整个方法。

我试过的代码:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){

var arrImageIdentifiers = String()


    if let thisAsset:PHAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
          arrImageIdentifiers.append(thisAsset.localIdentifier)

        //Get a reference to the camera view controller and call the savePhoto method
        let cameraVC = self.selectedViewController as? CameraViewController

        let manager = PHImageManager.default()

        manager.requestImage(for: thisAsset, targetSize: CGSize(width: 300.0, height: 300.0), contentMode: .aspectFit, options: nil, resultHandler: {(thisImage, _) in




        if let cameraVC = cameraVC {
            cameraVC.savePhoto(image: thisImage!)
        }
            })
        }
    self.dismiss(animated: true, completion: nil)
  }}

从上面的原始代码中获取照片元数据(创建日期、位置等)的最简单方法是什么?

extension PHAsset {
func metadata(_ completion: @escaping (Metadata?) -> Void) {
    let options = PHContentEditingInputRequestOptions()
    options.isNetworkAccessAllowed = true

    requestContentEditingInput(with: options) { input, _ in
        guard let url =  input?.fullSizeImageURL,
            let image = CIImage(contentsOf: url) else {
            completion(nil)
            return
        }
        let properties = image.properties
        let tiffDict = properties["{TIFF}"] as? [String: Any]
        let make = tiffDict?["Make"] as? String ?? ""
        completion(make)
    }
}


asset.metadata { metadata in
    guard let metadata = metadata else {
       return
    }
    // You can explore all available metadata values here. 
}

您从第一个代码获得的图像不包含元数据。您的第二个代码更接近正确;您需要返回 PHAsset 并从照片库中获取元数据。

This is what I tried but thisAsset always comes back nil

因为您忘记为照片库获取用户授权。否则,您将无法访问 PHAsset。