每当触发本地通知 并执行自定义操作时,我想从TabBarController
打开一个特定的ViewController
。我使用了以下一行代码:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier {
case "first":
DispatchQueue.main.async(execute: {
self.first()
})
case "second":
DispatchQueue.main.async(execute: {
self.second()
})
default:
break
}
completionHandler()
}
所以这是一个first()
函数:
func first() {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "Root") as! UITabBarController
let navigationController = storyboard.instantiateViewController(withIdentifier: "First") as! UINavigationController
tabBarController.present(navigationController, animated: true) {
}
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window?.tintColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
}
第二个函数:second()
func second() {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "Root") as! UITabBarController
let navigationController = storyboard.instantiateViewController(withIdentifier: "Second") as! UINavigationController
tabBarController.present(navigationController, animated: true) {
}
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window?.tintColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
}
它运行良好,但我无法打开第二个 ViewController
,而第一个出现并且第二个 notification 被触发:在控制台中:警告尝试呈现 ViewController...
最佳答案
使用这个:
tabBarController.selectedIndex = 1
或者这个:
tabBarController.selectedViewController = tabBarController.viewControllers![1]
1 可以是您的 tabBarController
呈现的任何 viewcontrollers
关于swift - 从 TabBarController 呈现一个特定的 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42239917/