我目前正在使用 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")
}
}
任何人都可以看到任何问题吗?