Swift 4.2
If you have a form in your app and if you might need a permission
change in your app you should store&restore the data. Because your app
might restart after a permission change (camera usage permission for
example).
Step 1: Add Restoration IDs to your UIViewController
s from Identity Inspector on your storyboard.
Step 2: Add these methods to AppDelegate
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
Step 3: Override these methods in your UIViewController
. Your data will stored in encodeRestorableState
method. And they will restored in decodeRestorableState
method.
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(self.myTextField.text ?? "", forKey: "myTextFieldRestorationKey")
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
if let txt = coder.decodeObject(forKey: "myTextFieldRestorationKey") as? String { self.myTextField.text = txt }
super.decodeRestorableState(with: coder)
}