我需要你的帮助。我需要将相机中的图片保存到ImageView中。当我打开应用程序时,图片必须出现在那里,但我不知道它是如何工作的。我是初学者,所以我非常感谢你的帮助/提示:) 谢谢。
更具体地说,我从手机拍了一张照片,图片出现了,但是当我关闭应用程序时,它就不再存在了。我应该使用NSUser Defaults ???
答案 0 :(得分:1)
如果要保存简单照片,可以使用UserDefaults。您需要将图像转换为NSData,然后您将能够保存在UserDefaults中。这是示例代码。
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Load saved image
loadImageFromUserDefaults()
}
private func loadImageFromUserDefaults() {
guard let imageData = UserDefaults.standard.data(forKey: "image_data") as NSData? else {
print("No image saved")
return
}
let image = UIImage(data: imageData as Data)
imageView.image = image
}
private func saveImageToUserDefaults(image: UIImage) {
guard let data = UIImageJPEGRepresentation(image, 1.0) as NSData? else {
print("Failed to convert image")
return
}
UserDefaults.standard.set(data, forKey: "image_data")
UserDefaults.standard.synchronize()
}
@IBAction func selectPhoto(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
self.present(imagePickerController, animated: true, completion: nil)
}
// UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
saveImageToUserDefaults(image: image)
loadImageFromUserDefaults()
}
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}