我有一个关于从AppDelegate实例化特定视图控制器的快速问题。我正在构建一个简单的聊天应用程序,需要在用户通过远程通知打开应用程序时进行响应。我的应用程序所需的行为是,当用户点击此通知时,应用程序将打开该特定的聊天屏幕。
该应用程序的基本流程如下:
我使用以下代码来显示正确的聊天屏幕。我可以点击后退按钮,它将按预期返回聊天列表。唯一的问题是导航控制器没有嵌入标签控制器中。这段代码是从func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler
调用的:
let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialVC : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ChatVC") as UIViewController
let detailVC : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "ChatDetailVC") as UIViewController
let navContr = UINavigationController(rootViewController:initialVC)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = navContr
self.window?.makeKeyAndVisible()
initialVC.navigationController?.pushViewController(detailVC, animated: true)
如何配置代码以使选项卡控制器成为堆栈的顶级?它在我的故事板中标记为“TabController”。
您只需创建一个标志,确定用户是来自通知点击还是正常启动
struct NotificationEvent {
static var isFromNotification = false
}
控制器的堆栈是 -
TabBarController-> UINavigationController-> ChatListViewController-> ChatDetailViewController
在AppDelegate func userNotificationCenter
-
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TabViewController") as! TabViewController//Your Tabbarcontroller
NotificationEvent.isFromNotification = true//recognize is from notification
window?.rootViewController = vc
ChatListViewController
class ChatListViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if NotificationEvent.isFromNotification {
openChatDetailScreen()//Jumps to that chat screen
NotificationEvent.isFromNotification = false
}
}
@IBAction func tapsOnChatList(_ sender: UIButton) {//consider it as didselect method in your tableView
openChatDetailScreen()
}
func openChatDetailScreen() {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatDetailViewController") as! ChatDetailViewController
navigationController?.pushViewController(vc, animated: true)
}
}
或者您也可以使用NotificationEvent.isFromNotification
/观察者检查特定viewcontroller中的通知事件,而不是UIApplicationLaunchOptionsKey.remoteNotification
。