【发布时间】:2018-08-09 08:52:33
【问题描述】:
我有一个tabBar。它的每个选项卡的ViewControllers 都嵌入在它们各自的NavigationControllers 中。
层次结构:
Tabbarcontroller --> NavigationController --> VC1 --> VC2 -->...VCn (for tab1)
当我单击推送通知时,我必须重定向到其中一个视图控制器说 VC2。我使用的代码如下。
let navigationController = UINavigationController()
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
if let chatViewController = storyboard.instantiateViewController(withIdentifier: "chatViewController") as? ChatViewController {
navigationController.viewControllers = [chatViewController]
window?.rootViewController = navigationController
}
通过使用它,我被重定向到相应的ViewController。但是,我无法回到tabBar。那么是否有可能以允许我返回标签栏的方式进行重定向,从而提供与 UI 中相同的层次结构?
编辑:
下图显示了我的布局。
我想完成以下工作:
-
当用户点击推送通知时,应用程序应被定向到 VC-B。 *如果 VC-B 已经在导航堆栈的顶部,则不应为 VC-B 创建新对象并添加到导航堆栈。
-
如果应用程序已被终止并且用户点击通知,它应该打开 VC-B。
为了确定应用程序是否已终止,我将标志设置为:
func applicationWillTerminate(_ application: UIApplication) {
UserDefaults.standard.set(true, forKey: UserDefaultsKey.isTerminated)
}
此标志在 didFinishLaunchingWithOptions 函数结束时设置为 false。
对于重定向,我检查此标志以确定应用程序是否已终止:
func performRedirectionToSuitableViewController(userInfo: [AnyHashable: Any]) {
let isTerminated = UserDefaults.standard.object(forKey: UserDefaultsKey.isTerminated) as! Bool
if isTerminated {
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let tab = storyboard.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController
tab.selectedIndex = 0
let nav = tab.viewControllers![0] as! UINavigationController
let chatViewController = storyboard.instantiateViewController(withIdentifier: "chatViewController") as! ChatViewController
chatViewController.chatThreadId = userInfo["thread_id"] as? String
nav.pushViewController(chatViewController, animated: true)
} else {
if let tab = window?.rootViewController?.presentedViewController as? UITabBarController {
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let chatViewController = storyboard.instantiateViewController(withIdentifier: "chatViewController") as! ChatViewController
chatViewController.chatThreadId = userInfo["thread_id"] as? String
if let nav = tab.selectedViewController as? UINavigationController {
nav.pushViewController(chatViewController, animated: true)
}
}
}
}
使用此代码,我的第一个要求已部分满足。需要确定 viewcontroller 是否位于导航堆栈的顶部。
并且,在应用程序终止的情况下,单击推送通知会打开标签栏,并选择默认选择索引。
我花了几天时间试图解决这个问题。但不能让它工作。
【问题讨论】:
-
你为什么要设置rootview控制器为什么不简单推送
-
当你从推送通知进入应用时,有一种可能,你不在你想去的地方,所以推送并不总是一个合适的选择
标签: ios swift push-notification uinavigationcontroller uitabbarcontroller