登录成功时,我正在使用KYDrawerController在主屏幕上显示侧边菜单。
我使用Alamofire请求用户身份验证,当响应成功时,然后用抽屉打开主屏幕。
问题是主屏幕没有显示或登录屏幕保持静止,但是当从Alamofire响应之外调用代码时,它工作得很好。这是我的代码
Alamofire.request(URL_LOGIN_PHONE, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success(let value):
let jsonResponse = JSON(value)
// Check if status = success
if jsonResponse["status"] == "success" {
// Init Drawer
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyBoard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let navVC = storyBoard.instantiateViewController(withIdentifier: "NavVC") // is the main controller for the drawer.
let drawerVC = storyBoard.instantiateViewController(withIdentifier: "DrawerVC") // is the drawer, and the drawer needs a main controller
appDelegate.drawerController.mainViewController = navVC
appDelegate.drawerController.drawerViewController = drawerVC
appDelegate.window?.rootViewController = appDelegate.drawerController
appDelegate.window?.makeKeyAndVisible()
} else {
}
case .failure( _):
}
}
您必须将代码放在异步闭包块中,就像这样
DispatchQueue.main.async {
// Init Drawer
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyBoard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let navVC = storyBoard.instantiateViewController(withIdentifier: "NavVC") // is the main controller for the drawer.
let drawerVC = storyBoard.instantiateViewController(withIdentifier: "DrawerVC") // is the drawer, and the drawer needs a main controller
appDelegate.drawerController.mainViewController = navVC
appDelegate.drawerController.drawerViewController = drawerVC
appDelegate.window?.rootViewController = appDelegate.drawerController
appDelegate.window?.makeKeyAndVisible()
}
问题与Alamofire或主线程无关,只是代码试图实例化已经加载的抽屉。所以我添加了代码来检查它是否已加载。如果已加载我使用unwindSegue返回主视图控制器。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// check if drawer loaded or not.
if appDelegate.drawerController.isViewLoaded {
// Drawer loaded prevoiusly, dont load it again
appDelegate.drawerController.setDrawerState(.closed, animated: true)
self.exitToRestaurants()
} else {
// Drawer not loaded from prevouis use.
// and it will be loaded for the first time/
let storyBoard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let navVC = storyBoard.instantiateViewController(withIdentifier: "NavVC") // is the main controller for the drawer.
let drawerVC = storyBoard.instantiateViewController(withIdentifier: "DrawerVC") // is the drawer, and the drawer needs a main controller
appDelegate.drawerController.mainViewController = navVC
appDelegate.drawerController.drawerViewController = drawerVC
appDelegate.window?.rootViewController = appDelegate.drawerController
appDelegate.window?.makeKeyAndVisible()
}