Swift4:使用userDefaults保存UIImages

时间:2019-03-19 10:55:07

标签: swift image uiview userdefaults

免责声明:我发现的任何内容都太旧或无法正常使用。

因此,我在ViewController中放置了一个与屏幕一样大的图像视图,并且由于有了imageButton,我可以将其设置为背景。现在,每次我使用该应用程序时,图像都不会出现。有什么方法可以使用userDefaults保存它?

 @IBOutlet weak var imageView: UIImageView!
    var imagePicker = UIImagePickerController()

@IBAction func imageButton(_ sender: UIButton) {
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = true
        present(imagePicker, animated: true, completion: nil)

    }

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
            imageView.image = image
        }
        dismiss(animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试

保存

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
            imageView.image = image
            if let data = image.pngData() {
               UserDefaults.standard.set(data, forKey: "YourKey")
            }
        }
        dismiss(animated: true, completion: nil)
    }
}
viewDidLoad内的

阅读

if let data = UserDefaults.standard.data(forKey: "YourKey") { 
    let image = UIImage(data: data)
}