首页 > 解决方案 > 如何防止从 Swift 中的 UIImagePickerController 自动保存图像?

问题描述

我的应用程序中有简单的场景。

我有 1 个编辑UIButton可以从照片库中选择图像并在UIImageView.

@IBAction func btnEdit(_ sender: UIButton) {

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary) {
        let picker:UIImagePickerController = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.delegate = self
        picker.allowsEditing = true
        picker.sourceType = .photoLibrary
        picker.navigationBar.isTranslucent = false
        self.present(picker, animated: true)
    } else {
        print("Photo Library is not available.")
    }

}

UINavigationControllerDelegate & UIImagePickerControllerDelegate

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

    if let pickedimage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
        self.imageView.image = pickedimage
    } else if let pickedimage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        self.imageView.image = pickedimage
    } else {
        print("Something went wrong while select photo from Library...!")
    }

    dismiss(animated: true, completion: nil)

}

它运作良好。但选定的图像会自动保存在 tmp 文件夹中

我不想保存在 Document 目录中。

在此处输入图像描述

如何停止在 Document 目录中自动保存图像?

标签: iosswiftuiimageviewswift4uiimagepickercontroller

解决方案


UIImagePickerController.InfoKey 是否包含 imageURL 键的值?
如果是这样,它是否映射到您的 tmp 目录中的这个位置?

我对文档的理解是 UIImagePickerController 创建了一个供您的应用使用的图像的副本,因此您可以操作它而不必担心影响用户的图像库。该副本存储在 tmp 目录中。如果您出于某种原因想要清除该副本,您有责任删除该图像。

来自 iOS 应用程序文件系统上的 Apple 文档(已添加重点):

温度/

使用此目录来编写不需要在应用程序启动之间保留的临时文件。当不再需要文件时,您的应用应从该目录中删除文件;但是,当您的应用程序未运行时,系统可能会清除此目录。此目录的内容不由 iTunes 或 iCloud 备份。

https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW4

假设您捕获 imageURL,此清理工作将是:

let fmTmp = FileManager.default
try! fmTmp.removeItem(at: theImageURL)

推荐阅读