iosswiftuitabbarcontrollerappdelegateremote-notifications

how to redirect user to various screen based on remote notification type


I am receiving remote notification's in my application. Following code is written in AppDelegate file which called when i receive notification.

get notification when app is in background

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("Notification Recieved")

    UIApplication.shared.applicationIconBadgeNumber += 1

    //process notification

    for (key,val) in userInfo{

        let nkey = key as! String

        if nkey == "notificationType"{
            let notificationType = val as! String

            handleNotificationScreen(type: notificationType)
        }
    }
}

Above function get called when app is in background and user clicks on notification in that function userInfo is a payload which contains info of notification. In userInfo I am passing notificationType from server which contains various values like TASK,KRA etc

Now based on these notificationType values I want to launch different screens. If notificationType is TASK Then launch Task Screen when user clicks on notification.

I have a TabBarController which have multiple viewControllers

viewControllers = [taskController,messageController,notificationConroller,userProfileNavigationController,empCorner,perfomranceVC]

Now what should I do to launch screen in my handleNotificationScreen(type: notificationType) function.

func handleNotificationScreen(type: String){

        switch type {
        case "KRA":
            print("anc")
        case "TASK":
            print("task")
        case "EMPMONTH":
            print("empMonth")
        default:
            print("none")
        }
    }

Thank you guys for any help.


Solution

  • Get the reference of your TabBarController and inside handleNotificationScreen , if you want to get TabBarControllers inside in Appdelegate, Declare property optional like this.

    var tabbarController: UITabBarController?
    

    inside didFinishLaunchingWithOptions function call this

    tabbarController = self.window?.rootViewController as? UITabBarController

    Now can use tabbarController to call your specific controller in your desired function.

    func handleNotificationScreen(type: String){
    
        switch type {
        case "KRA":
            print("anc")
        case "TASK":
            print("task")
            tabBarController?.selectedIndex = 0 //it will open taskbarcontroler
        case "EMPMONTH":
            print("empMonth")
        default:
            print("none")
        }
    }