使用本机API保存和还原应用程序状态

时间:2019-10-30 03:25:32

标签: ios swift restore

我正在尝试实现应用程序的保存/恢复状态。

我拥有的代码:

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。

例如,我想选择第二个选项卡-应用终止恢复并重新启动后,它应该显示第二个选项卡已打开。 我认为应在应用终止时执行编码。但这没有被调用。而且解码也没有调用。我做错了什么?预先感谢!

0 个答案:

没有答案