Я пытаюсь реализовать сохранение / восстановление состояния приложения.
Этот код у меня есть:
В AppDelegate
Я добавил:
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
Затем у меня есть реализация TabBarController, которая соответствует восстановлению:
final class TabBarViewController: UITabBarController {
init() {
super.init(nibName: nil, bundle: nil)
restorationIdentifier = "ContainerVC"
restorationClass = type(of: self)
let vc1 = ViewController(with: .green)
let vc2 = ViewController(with: .red)
vc1.tabBarItem = .init(title: "green", image: nil, tag: 0)
vc2.tabBarItem = .init(title: "red", image: nil, tag: 1)
self.viewControllers = [vc1, vc2]
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TabBarViewController: UIViewControllerRestoration {
static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? {
let vc = TabBarViewController()
vc.selectedIndex = coder.decodeInteger(forKey: "index")
return vc
}
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(self.selectedIndex, forKey: "index")
print("encoded")
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
self.selectedIndex = coder.decodeInteger(forKey: "index")
super.decodeRestorableState(with: coder)
}
}
Также TabBarViewController является корневым ViewController окна приложения.
Я хочу, например, выбрать вторую вкладку - после приложениязавершил восстановление и снова запустил приложение, которое должно показать вторую открытую вкладкуЯ думаю, что кодирование должно выполняться после завершения работы приложения. Но это не называется. И расшифровка тоже не называется. Что я делаю не так? Заранее спасибо!