1

我目前正在使用 Realm 设计一个数据库管理应用程序,我已经成功地创建和检索了一个对象。我遇到的问题是更新/编辑 - 特别是更新用户上传的 UIImage 。使用 Realm,我保存图像的路径,然后通过加载该路径(在文档目录中)来检索它。

当用户尝试保存更改的图像时,出于某种奇怪的原因,UIImageJPEGRepresentation将更改的图像保存为 nil,从而删除了用户的图像。这很奇怪,因为数据对象的初始创建很好地存储了它。

我试图通过一些调试检查图像是否正确传递,并发现它做得很好并且正确的路径正在保存。

这是我的更新方法:

func  updateImage() { 
    let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let fileURL = documentsDirectoryURL.appendingPathComponent("\(selectedPicPath!)")

    if FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            if profilePic.image != nil {
            let image = profilePic.image!.generateJPEGRepresentation()
            try! image.write(to: fileURL, options: .atomicWrite)
            }
        } catch {
            print(error)
        }
    } else {
            print("Image Not Added")
    }
}

任何人都可以看到任何问题吗?

4

1 回答 1

3
let image = profilePic.image!.generateJPEGRepresentation()

检查这一行,是否返回零值或数据?如果为零,则使用以下代码测试您的图像存储,它正在工作。还要确保您的实际图像具有您尝试生成的 JPEG 文件格式扩展名。

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

// 对于 PNG 图像

if let image = UIImage(named: "example.png") {
    if let data = UIImagePNGRepresentation() {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

对于 JPG 图像

if let image = UIImage(named: "example.jpg") {
    if let data = UIImageJPEGRepresentation(image, 1.0) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.jpg")
        try? data.write(to: filename)
    }
}
于 2017-02-25T02:10:38.317 回答