尝试在USerDefault中保存图像时我做错了什么

时间:2018-07-10 02:05:43

标签: ios swift nsuserdefaults

我必须先获取图像,然后将其保存到UserDefaults中才能进行检索。但是,我尝试将其另存为UIImage,但是当我尝试检索图像时,应用程序崩溃了。对我而言,最好的方法是什么?

这就是我要保存图片的方式。

import UIKit

protocol dataReceivedDelegate {
    func dataReceived(fotoSaved:[UIImage],nameSaved:NSArray)
}

class adicionarNovoItemVc: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {

    @IBOutlet weak var textFieldNome: UITextField!
    let imagePicker = UIImagePickerController()
    @IBOutlet weak var namePreview: UILabel!
    @IBOutlet weak var imagePreview: UIImageView!
    let picker = UIImagePickerController()
    var arrayName = [String]()
    var arrayFoto = [UIImage]()
    var delegate:dataReceivedDelegate? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textFieldNome.delegate = self
        // Do any additional setup after loading the view.
        if isKeyPresentInUserDefaults(key: "namesSavedArray") == true{
            arrayName = UserDefaults.standard.array(forKey: "namesSavedArray") as! [String]
        }
        if isKeyPresentInUserDefaults(key: "fotoSavedArray") == true{
            arrayFoto = UserDefaults.standard.array(forKey: "fotoSavedArray") as! [UIImage]
        }
    }
    func isKeyPresentInUserDefaults(key: String) -> Bool {
        return UserDefaults.standard.object(forKey: key) != nil
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
            self.imagePreview.image = image
            self.namePreview.text = self.textFieldNome.text
        }
        self.picker.dismiss(animated: true, completion: nil)
    }


    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.textFieldNome.resignFirstResponder()
        return true
    }

    @IBAction func botaoAdcItem(_ sender: UIButton) {
        if (self.namePreview!.text != nil) && (self.imagePreview!.image != nil) {
            if delegate != nil {

                arrayName.append(self.namePreview.text!)
                arrayFoto.append(self.imagePreview.image!)

                delegate?.dataReceived(fotoSaved: arrayFoto, nameSaved: arrayName as NSArray)

                UserDefaults.standard.set(arrayName, forKey: "namesSavedArray")
                UserDefaults.standard.set(arrayFoto, forKey: "fotoSavedArray")

            self.navigationController?.popViewController(animated: true)
            }
        }
        else {return}
}

2 个答案:

答案 0 :(得分:2)

您不能也不应将图像存储到UserDefaultsUserDefaults用于保留简短内容,例如用户输入的字符串或首选项设置。

它只能保存简短的数据类型列表(“属性列表”对象:数组,字典,字符串,数据,日期,整数类型,浮点类型或布尔型)。任何其他数据类型都将失败。

我建议将图像保存到用户的Documents目录中,然后在UserDefaults中保存文件的路径。

答案 1 :(得分:0)

正如@ Duncan-c所说,您不应将其保存在UserDefaults中。 您可以在UserDefaults中保存选定的文件名(URL) 并在下次要使用文件名(URL)加载实际图像时使用。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
  if let imageURL = info[UIImagePickerControllerImageURL] as! URL? {
    UserDefaults.standard.set(imageURL, forKey: "SelectedImage")
    UserDefaults.standard.synchronize()
  }

  ...  
  picker.dismiss(animated: true, completion: nil)

}

// Load the image
if let imageURL = UserDefaults.standard.url(forKey: "SelectedImage") {
   if let data = NSData(contentsOf: imageURL) as NSData? {
      self. imagePreview.image = UIImage(data: data as Data)
   }
}