我用post方法编写函数以推送到ViewController。在post方法中,我得到了用户的类型,并且按类型,我应该推送到不同的ViewControllers

class GetUser:NSObject {
    class func restartapp() {
        guard let window = UIApplication.shared.keyWindow else {return}
        var url = baseurl + "/get-user/"
        var param = ["token":APItoken.getToken()!]
        window.makeKeyAndVisible()
        Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            switch response.result {
            case.failure(let err):
                print(err)
            case.success(let val):
                var json = JSON(val)
                print(json)
                if json["user"]["role_id"].intValue == 2 {
                    window.rootViewController = UINavigationController.init(rootViewController: DriverMainPage())
                }
                if json["user"]["role_id"].intValue == 1 {
                    window.rootViewController = UINavigationController.init(rootViewController: MainPageController())
                }
            }
        }
        UIView.transition(with: window, duration: 0.5, options: .transitionCurlDown, animations: nil, completion: nil)
    }

}


当我在AppDelegate中返回此代码时,出现错误NSException

最佳答案

尝试在主线程上运行成功块,例如

重置根控制器:

DispatchQueue.main.async {
    if json["user"]["role_id"].intValue == 2 {
        window.rootViewController = UINavigationController.init(rootViewController: DriverMainPage())
    }
    if json["user"]["role_id"].intValue == 1 {
        window.rootViewController = UINavigationController.init(rootViewController: MainPageController())
    }
}


推入根控制器:

DispatchQueue.main.async {
   if json["user"]["role_id"].intValue == 2 {
        (window.rootViewController as? UINavigationController)?.pushViewController(DriverMainPage(), animated: true)
   }
   if json["user"]["role_id"].intValue == 1 {
        (window.rootViewController as? UINavigationController)?.pushViewController(MainPageController(), animated: true)
   }
}

09-27 23:13