簡単な写真を保存する場合は、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)
}
}
ありがとうございました!私はApp.I本当にあなたの助けに感謝して実行するたびに、 "ImageView"の画像を示しています! :D –
ようこそ、もちろん問題ありません! – muazhud