0

I need to store ViewControllers created by the user into a json file and I need to recreate them on either the same device or a different device later on.

The ViewControllers are available in the storyboard but I am not able to properly instantiate them in the init(from decoder: Decoder) function.

This is the ViewController to be saved and restored.

class SecondViewController: UIViewController, Encodable, Decodable {
@IBOutlet weak var textField: UITextField!

   private var restoreText: String?

   enum CodingKeys: CodingKey {
      case textField
   }

   func encode(to encoder: Encoder) throws {
      var container = encoder.container(keyedBy: CodingKeys.self)
      try container.encode(textField.text, forKey: .textField)
   }

   required init(from decoder: Decoder) throws {
       let container = try decoder.container(keyedBy: CodingKeys.self)
       restoreText = try? container.decode(String.self, forKey: .textField)
       super.init(nibName: "", bundle: nil)
   }

   required init?(coder: NSCoder) {
       super.init(coder: coder)
   }

   override func viewDidLoad() {
       super.viewDidLoad()
       if let text = restoreText {
          textField.text = text
       }
   }

   @IBAction func save(_ sender: Any) {
      do {
        let jsonData = try JSONEncoder().encode(self)
        let s = String(data: jsonData, encoding: .ascii)
        print("Widgets \(s!)")

        let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
        try jsonData.write(to: filename)
      } catch {
        print(error.localizedDescription)
      }
  }
}

This is where I load the controller from the json file and I try to recreate it.

...

do {
      let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
      let jsonData = try Data(contentsOf: filename)
      if let s = String(data: jsonData, encoding: .ascii) {
         let controller = try JSONDecoder().decode(SecondViewController.self, from: jsonData)
         let frame = CGRect(x: 0, y: 0, width: view.frame.width * 0.8, height: view.frame.height * 0.8)
         controller.view.frame = frame
         controller.view.center = view.center
         view.addSubview(controller.view)
         addChild(controller)
      }
    } catch {
        print(error.localizedDescription)
    }
...

Running this the code I get the following error:

*** Assertion failure in -[UINib initWithNibName:directory:bundle:], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3920.26.113/UINib.m:97
2020-04-18 09:44:03.543891+0200 ViewControllerSerialization[7764:504964] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: (name != nil) && ([name length] > 0)'

As far as I understand this error is because the controller has not be loaded from the storyboard.

Question is how do I correctly initialize the ViewController from the storyboard in the init(from decoder: Decoder) function?

Fab
  • 1,468
  • 1
  • 16
  • 37
  • https://stackoverflow.com/questions/30449137/custom-init-of-uiviewcontroller-from-storyboard https://stackoverflow.com/questions/24035984/instantiate-and-present-a-viewcontroller-in-swift etc. – Larme Apr 18 '20 at 08:16
  • But that's strange. " to store ViewControllers created by the user into a json": I would'd go this way instead: I need to save CustomViewModel into JSON, and be able to init a ViewController with that custom model. – Larme Apr 18 '20 at 08:17
  • you have the error because you're encoding String.self form text field and trying to decode it to SecondViewController.self, types are mismatched – Dialogue Apr 18 '20 at 08:33

0 Answers0