登录用户会崩溃应用程序

时间:2017-12-29 17:21:55

标签: ios swift nsnotificationcenter

在我的SettingsVC中,我发送了NSNotification.Name(rawValue: "LogOut")的通知,该通知由AppDelegate的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
}

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

1 个答案:

答案 0 :(得分: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)
  }
}