问题描述
我正在尝试在我的应用程序中实现状态恢复,我已经阅读了许多文章和文档,但到目前为止,我还无法使其正常工作。我给所有视图控制器一个恢复ID,并且(我认为)具有使它正常工作的所有必要功能。
在AppDelegate
func application(_ application: UIApplication,willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
func application(_ application: UIApplication,shouldRestoreSecureApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication,shouldSaveSecureApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication,viewControllerWithRestorationIdentifierPath identifierComponents: [String],coder: NSCoder) -> UIViewController? {
return coder.decodeObject(forKey: "Restoration ID") as? UIViewController
}
func application(_ application: UIApplication,didDecodeRestorableStateWith coder: NSCoder) {
UIApplication.shared.extendStateRestoration()
dispatchQueue.main.async {
UIApplication.shared.completeStateRestoration()
}
}
在我的视图控制器中:
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
getSetDataFromTable()
coder.encode(currentSession,forKey: "CurrentSession")
}
override func decodeRestorableState(with coder: NSCoder) {
super.decodeRestorableState(with: coder)
self.currentSession = coder.decodeObject(forKey: "CurrentSession") as! [CurrentSessionElement]
}
override func applicationFinishedRestoringState() {
tableView.reloadData()
}
static func viewController(withRestorationIdentifierPath identifierComponents: [String],coder: NSCoder) -> UIViewController? {
guard let restoredSession = coder.decodeObject(forKey: "CurrentSession") as? [CurrentSessionElement] else {
print("decoding user detail")
return nil
}
let vc = CurrentSessionVC()
vc.currentSession = restoredSession
return vc
}
我在所有功能中都设置了断点,当我尝试测试功能时,命中的断点是
加载时:
shouldRestoreSecureApplicationState
didDecodeRestorableStateWith
清除应用程序时:
shouldSaveSecureApplicationState
在测试时没有任何恢复,并且没有触发任何视图控制器功能,我丢失了什么吗?
解决方法
我遇到了同样的问题。我删除了 SceneDelegate 并且一切都开始正常工作。据我了解,SwiftUI 的恢复以另一种方式工作,与经典 UI 流程不兼容
,看看this。不建议远离 SceneDelegate。