微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在iOS 14中实现状态恢复

如何解决在iOS 14中实现状态恢复

我正在尝试在我的应用程序中实现状态恢复,我已经阅读了许多文章和文档,但到目前为止,我还无法使其正常工作。我给所有视图控制器一个恢复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。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。