在我的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
}
崩溃发生时没有任何其他信息。知道如何让这不崩溃吗?谢谢!
我认为你应该在调用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)
}
}