gpt4 book ai didi

ios - 将照片库中的图像加载到我的 UIImageView 中,但重新启动应用程序时图像不会更改

转载 作者:行者123 更新时间:2023-11-29 05:47:41 26 4
gpt4 key购买 nike

我有 imageView 和一个按钮,用于从照片库上传图像并将其保存在 imageView 中,因此当我将照片上传到 imageView 时,即使我关闭应用程序,它也会将图像保存在 imageView 中。

但我的问题是,每当我上传新照片时,它都会毫无问题地改变。但是当我关闭应用程序并再次启动它时,旧照片又回来了。

func saveImage(image : UIImage, imageName: String){
let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let fileURL = documentDirectoryPath.appendingPathComponent(imageName)
if let data = UIImageJPEGRepresentation(image, 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
do {
try data.write(to: fileURL)
print("Image saved")
} catch {
print("Image save error:", error)
}
}
}

func getImage(imageName: String) -> UIImage?{
let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentDirectoryPath.appendingPathComponent(imageName)
let image = UIImage(contentsOfFile: fileURL.path)
return image
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
imageView.image = image
saveImage(image:image!, imageName: "profile.jpg")
picker.dismiss(animated: true, completion: nil)
}

override func viewDidLoad() {
super.viewDidLoad()

if let image = getImage(imageName: "profile.jpg"){
imageView.image = image}
}

我期待图像更改,即使关闭应用程序也会保存。

但实际上它总是返回到我上传的第一张图片。

最佳答案

看起来在 saveImage 中,您正在检查文件是否已经存在,如果存在则不进行保存。这意味着您第一次选择图像时,它将正确保存,但任何进一步的图像选择都会更新控件,但不会更新文件,这将导致您下次打开应用程序时再次出现旧图像。因此,您可能希望从 if 中完全删除 fileExists 检查。

您可以通过向执行 print() 的 saveImage 中的 if 语句添加 else 来验证所发生的情况,当您第二次选择图像时,它应该出现在您的日志文件中:

if let data = UIImageJPEGRepresentation(image, 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
// ...
}
else {
print("File exists -- image not saved")
}

关于ios - 将照片库中的图像加载到我的 UIImageView 中,但重新启动应用程序时图像不会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com