登录用户会崩溃应用程序

问题描述 投票:1回答:1

在我的SettingsVC中,我发送了一个由AppDelegate的NSNotification.Name(rawValue: "LogOut")函数观察到的didFinishLaunchingWithOptions通知。

收到通知后,我调用User.logout清除所有用户数据,然后应用程序在DispatchQueue块中崩溃。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.backgroundColor = .white

    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "LogOut"), object: nil, queue: nil) { _ in
        User.logout()

        DispatchQueue.main.sync {
            self.navigationController?.setViewControllers([WelcomeViewController()], animated: false)
        }
    }

    if let _ = UserDefaults.standard.string(forKey: "loggedIn") {
        self.navigationController = UINavigationController(rootViewController: HomeViewController())
    } else {
        self.navigationController = UINavigationController(rootViewController: WelcomeViewController())
    }

    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()

    return true
}

崩溃发生时没有任何其他信息。知道如何让这不崩溃吗?谢谢!

ios swift nsnotificationcenter
1个回答
2
投票

我认为你应该在调用setViewControllers之前“清除”导航堆栈,而且:

在退出之前从后台线程同步启动主线程

在逻辑上是错误的,以这种方式更好地使用async

NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "LogOut"), object: nil, queue: nil) { _ in
  User.logout()
  DispatchQueue.main.async {
    self.navigationController?.popToRootViewController(animated: false)
    self.navigationController?.setViewControllers([WelcomeViewController()], animated: false)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.