【发布时间】: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)
}
【问题讨论】:
-
您永远不会保存第二张图片,因为您只保存不存在的图片。