【问题标题】:How do I change the value stored in a image file in swift 4如何在 swift 4 中更改存储在图像文件中的值
【发布时间】:2018-09-14 17:25:22
【问题描述】:

我保存了我的第一张图片并加载,但是当我保存第二张图片时,按钮的图片与我保存的第一张图片保持一致。有人可以告诉我如何让这些文件的值能够改变吗?

这是当有人选择图像时运行的代码:

        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        // choose a name for your image
        let fileName = "image.jpg"
        // create the destination file url to save your image
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        // get your UIImage jpeg data representation and check if the destination file url already exists
        if let data = UIImageJPEGRepresentation(pickedImage, 1.0),
            !FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                // writes the image data to disk
                try data.write(to: fileURL)
                print("file saved")
            } catch {
                print("error saving file:", error)
            }
        }

        if let image = getSavedImage(named: "image.jpg") { Button1.setImage(image, for: .normal)
        }

这是我在加载视图时的代码:

 if let image = getSavedImage(named: "image.jpg") {
        Button1.setImage(image, for: .normal)
    }

【问题讨论】:

  • 您永远不会保存第二张图片,因为您只保存不存在的图片。

标签: ios swift image file


【解决方案1】:

正如@rmaddy 提到的,您已经保存了图像,这就是图像未被替换的原因。但是如果你想点击按钮图像会改变你需要做一些额外的工作,你需要检查image.jpg是否存在然后添加具有差异名称的新图像。要检查图像是否存在,请使用此方法,此方法返回布尔值和文件的路径(如果文件存在)。因此,根据您的代码行为,在这两个值上,您可以删除现有图像或创建具有不同名称的新图像。

static func isFileExit(filename: String) -> (fileExist: Bool? , path: URL?) {


    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        let filepath =  URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(filename)
        let fileManager = FileManager.default

        if fileManager.fileExists(atPath: filepath.path) {
            print("FILEAVAILABLE")
            return (true, filepath)
        }

    }

    return (false,nil)
}

【讨论】:

    【解决方案2】:

    您仅在图像不存在时才保存图像,因此当您尝试保存第二张图像时,它不会被保存,因为第一张图像已经存在。

    //you should double check what you're doing here
        if let data = UIImageJPEGRepresentation(pickedImage, 1.0),
                    !FileManager.default.fileExists(atPath: fileURL.path) {
                    do {
                        // writes the image data to disk
                        try data.write(to: fileURL)
                        print("file saved")
                    } catch {
                        print("error saving file:", error)
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-01
      • 2015-01-06
      • 2012-06-11
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多