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

jum4pzuy  于 2022-11-19  发布在  iOS
关注(0)|答案(2)|浏览(258)

我尝试获取此工作代码,该代码通过selectedImage从ImagePicker检索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总是返回零,所以它基本上跳过了整个方法。

我尝试的代码:

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)
  }}

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

thtygnil

thtygnil1#

从 第 一 个 代码 中 得到 的 图像 不 包含 元 数据 。 第 二 个 代码 更 接近 正确 ;您 需要 返回 PHAsset 并 从 照片 库 中 获取 元 数据 。
我 试 过 了 , 但 thisAsset 总是 返回 零
因为 您 忘记 获得 照片 库 的 * 用户 授权 * 。 没有 该 授权 , 您 无法 访问 PHAsset 。

mwecs4sa

mwecs4sa2#

extension PHAsset {
    func metadata(_ completion: @escaping (String?) -> 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.
}

相关问题