Change tabbarindex when push notification is pressed

Viewed 40

I have an app that receive push notifications. When I press the notification, I want to navigate to first index of my UITabBarController , it has to do it when the app is opened or not. My base index is the second one , I mean , index = 1 and the first index is 0 that is my view controller goal. I already tested some code in AppDelegate but it doesn't work. I`m using OneSignal Service, Any ideas ? thanks.

This code is in didFinishLaunchingWithOptions function

 let notificationOption = launchOptions?[.remoteNotification]
    if let notification  = notificationOption as? [AnyHashable : Any]{
        print(notification)
        (window?.rootViewController as? UITabBarController)?.selectedIndex = 0
    }

and this code is in didReceiveRemoteNotification function

print(userInfo)
    (window?.rootViewController as? UITabBarController)?.selectedIndex = 0
1 Answers
let KAppDelegate = (UIApplication.shared.delegate as! AppDelegate)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
         let userInfo = response.notification.request.content.userInfo
        let strNotification = String(format: "Action Identifier : %@, UserInfo Dict : %@", response.actionIdentifier, userInfo)
        print(strNotification)
        handleNotification(userInfo: userInfo)
        completionHandler()
    }

func handleNotification(userInfo : [AnyHashable : Any]) {
        if let appNav = KAppDelegate.window?.rootViewController as? UINavigationController{
    if let objTabbarController = appNav.viewControllers.first as? UITabBarController{
        if let objTempNotificationController = objTabbarController.selectedViewController {
            if !objTempNotificationController.isKind(of: "Your controller name like NotificationViewController".classForCoder()){
                objTabbarController.selectedViewController = objTabbarController.viewControllers![0]
                appNav.popToRootViewController(animated: true)
            }
        }else{
         //failure to not get object
        }
    }else{
        //failure to not get object
    }
    }
Related