Swift - How to Open Specific View Controller When Push Notification Received

Swift - How to open specific view controller when push notification received?

When you app is in closed state you should check for launch option in

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { }

and call your API.

Example:

if let option = launchOptions {
let info = option[UIApplicationLaunchOptionsKey.remoteNotification]
if (info != nil) {
goAnotherVC()
}
}

Open app in specific view when user taps on push notification with iOS 13 Swift 5

You can trigger a notification once you receive and the user clicks on the notification.

Along with the notification, you can pass the value which will later used to identify to which view controller you need to navigate.

Create a class which will be responsible for all the push notification navigation handling. You can name it like PushNotificationHandler. Let the PushNotificationHandler handler take care of all the logic to navigate to the view controllers.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
}
  • Get the value from the deep link using the above delegate method
  • Trigger a notification with the value
  • Handle the notification inside PushNotificationHandler class

Open specific ViewController from push notification when application closed

If you want to open vc from the closed state of your app, you can check if app was opened from click on Notification in this method of AppDelegate.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 

It looks like:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

// When the app launch after user tap on notification (originally was not running / not in background)
if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {

goToEventDetails(userInfo: launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any])

}
}

Where goToEventDetails is method which instantiates VC and pushed id, and [UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] is content of Notification.

How do I open a particular view controller in a tab bar when a FCM push notification is tapped?

Here is the code to my explanation

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

if let window = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window {
if let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController {
if let tabBarController = rootViewController as? MainTabBarController {
tabBarController.selectedIndex = 1
window.rootViewController = tabBarController
window.makeKeyAndVisible()
}
} else {
let tabBarController = UIStoryboard(name: "main", bundle: .main).instantiateViewController(identifier: "MainTabBarController") as? MainTabBarController
tabBarController.selectedIndex = 1
window.rootViewController = tabBarController
window.makeKeyAndVisible()
}
}
completionHandler()
}

How to go directly to a specific View Controller if Notification has been opened

didFinishLaunchingWithOptions is not necessarily called, when you click on a notification, only if your app is not in the memory anymore

In your willFinishLaunchingWithOptions function of your appDelegate, set up a delegate for the currentNotificationCenter

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
}

Make sure your AppDelegate implements UNUserNotificationCenterDelegate relevant for you could be this

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let chatID = userInfo["chatID"] as? String {
// here you can instantiate / select the viewController and present it
}
completionHandler()
}

Update to answer your follow-up question: How to add a UIViewController to a UINavigationController within your UITabbarController

In order to instantiate your ViewController and add it to your UITabbarController:

let myViewController = MyViewController() 
guard let tabbarController = self.window.rootViewController as? UITabbarController else {
// your rootViewController is no UITabbarController
return
}
guard let selectedNavigationController = tabbarController.selectedViewController as? UINavigationController else {
// the selected viewController in your tabbarController is no navigationController!
return
}
selectedNavigationController.pushViewController(myViewController, animated: true)

How to Open a Specific View Controller On didReceiveRemoteNotification when application is in back ground

1.Firstly you should Turn On Background Fetch in app "Capabilities"
2. Then use following code in app delegate

In AppDelegate class add following code:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// print(userInfo)
let vc = mainStoryBoard.instantiateViewController(withIdentifier: "destinationVC") as! destinationVC
self.visibleNavController.pushViewController(vc, animated: true)
}

For iOS 10 use following code:
1.Import

 import UserNotifications

For foreground fetch

     @available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
var userInfo = NSDictionary()
userInfo = notification.request.content.userInfo as NSDictionary
let pay = userInfo as NSDictionary
let driverLocationVC = mainStoryBoard.instantiateViewController(withIdentifier: "destinationVC") as! destinationVC
self.visibleNavController.pushViewController(driverLocationVC, animated: true)

}

For the background

 @available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Userinfo \(response.notification.request.content.userInfo)")

var userInfo = NSDictionary()
userInfo = response.notification.request.content.userInfo as NSDictionary
print(userInfo)
let driverLocationVC = mainStoryBoard.instantiateViewController(withIdentifier: "DriverLocationVC") as! DriverLocationVC
self.visibleNavController.pushViewController(driverLocationVC, animated: true)
}

For device token fetch

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Got token data! \(tokenString)")

UserDefaults.standard.set(tokenString, forKey: "device_token")
UserDefaults.standard.synchronize()
}


Related Topics



Leave a reply



Submit