首页 > 解决方案 > 在没有 StoryBoard 的情况下点击通知时访问特定的 ViewController(以编程方式)

问题描述

我有一个包含 3 个选项卡的应用程序: - 主页 - 收件箱 - 个人资料

当用户收到通知时,我想打开相应的聊天,当用户按下后退按钮时,我希望能够打开收件箱选项卡。

我拥有的以下代码是这样的:

     func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    didReceive response: UNNotificationResponse,
                                    withCompletionHandler completionHandler: @escaping () -> Void) {

            let notificationContent = response.notification.request.content

            switch notificationContent.categoryIdentifier {

            case "ChatViewController":

                let tabBarVC = self.window?.rootViewController as! MainTabViewController

                tabBarVC.selectedIndex = 1 // This is the Inbox tab

                let chatVC = ChatViewController(collectionViewLayout: UICollectionViewFlowLayout())

                let inboxVC = InboxViewController()

                inboxVC.navigationController?.pushViewController(chatVC, animated: true)

            default:
                return
            }


            completionHandler()
        }

然而,在这一行之后tabBarVC.selectedIndex = 1,代码没有被读取,它打开了InboxViewController,为什么会这样,我怎样才能打开聊天?

标签: iosswiftnotificationsviewcontroller

解决方案


使用它对所选控制器的检查太简单了

let selectedController = tabBarVC.selectedViewController? 

和全功能

          func userNotificationCenter(_ center: UNUserNotificationCenter,
                                        didReceive response: UNNotificationResponse,
                                        withCompletionHandler completionHandler: @escaping () -> Void) {

                let notificationContent = response.notification.request.content

                switch notificationContent.categoryIdentifier {

                case "ChatViewController":

                    let tabBarVC = self.window?.rootViewController as! MainTabViewController

                    tabBarVC.selectedIndex = 1 // This is the Inbox tab

                    let chatVC = ChatViewController(collectionViewLayout: UICollectionViewFlowLayout())

              if let selectedController = tabBarVC?.selectedViewController as? InboxViewController
        {
            selectedController?.navigationController?.pushViewController(chatVC, animated: true)
        }               

                default:
                    return
                }


                completionHandler()
            }

推荐阅读