How to Make Your Push Notification Open a Certain View Controller

How to make your push notification Open a certain view controller?

You can detect if the app opened from the notification with this code in app delegate. You will need to set the initial view controller when the application state is UIApplicationStateInactive before the app has become active. You can perform any logic there to decide which view controller should be opened and what content should be shown in that view controller.

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

if(application.applicationState == UIApplicationStateActive) {

//app is currently active, can update badges count here

} else if(application.applicationState == UIApplicationStateBackground){

//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here

} else if(application.applicationState == UIApplicationStateInactive){

//app is transitioning from background to foreground (user taps notification), do what you need when user taps here

self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];

self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];

}

}

Open view controller when receiving remote Push Notification

Please try the following code:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
NotificationViewController *notificationViewController = [[NotificationViewController alloc] init];
[navController.visibleViewController.navigationController pushViewController:notificationViewController];
}

How to Open a Notification view controller when a iOS push notification is received?

For Kill State OR Terminate State:

Define new property in AppDelegate.swift file

var isFromNotification = false

Make below changes in AppDelegate.swift and keep rest of code as it is.

if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {
isFromNotification = true
//other required code
}

Goto your Homepage.swift file

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated).

let appDelegate = UIApplication.shared.delegate as! AppDelegate
if appDelegate.isFromNotification {
appDelegate.isFromNotification = false
//Push to your notification controler without animation
}
}

Update: For Background and Foreground State

Above answer is only work for Kill state as mention in the comment by @Abu Ul Hassan

Now, Let's understand the flow about the background or foreground state.

userNotificationCenter(_:didReceive:withCompletionHandler:) method is called when a user clicks on the notification in background or foreground mode.

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//other required code
//Get current navigation controller and redirect into notification screen
completionHandler()
}

How to grab current UIViewController or current UINavigationController

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.

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()
}
}

Load a specific viewController on push notification Swift 2 AppDelegate

I want to respond to my own question because I think maybe someone is facing the same situation, I have to say thanks to @Muneeba

Well, first of all you have to know if your remote push notification needs to do a background fetch, this is important because if so the didReceiveRemoteNotification is called twice (first when you click on the notification alert, seconds when it opens the app), so you have to be aware of this.

In my case I didn't do a background fetch, so my content-available:false flag was set to false.

Next thing to do is add you desire ["key":value] to the notification payload to know whether you want to open a specific view controller or not.

Manage whether open a view controller or not.

In my app I want to open a alert control pop up always showing the body of the push notification (with a OK button) and only when certain value is set open a alert control with a question to the user whether or not he wants to open the new content that arrives (normally this content is a web based content that open a webview embedded in a view controller)

In the didReceiveRemoteNotification:

if let mensaje = userInfo["m"] as? String {
// Here is where I know if the value is set in the notification payload
let alertCtrl = UIAlertController(title: titulo, message: mensaje as String, preferredStyle: UIAlertControllerStyle.Alert)
if url == nil {
alertCtrl.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
} else {
alertCtrl.addAction(UIAlertAction(title: "Ver receta", style: .Default, handler: {
action in

let storyboard = UIStoryboard(name: "Main", bundle: nil)
//self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("TabbedController") as! UITabBarController
let navigationController = storyboard.instantiateViewControllerWithIdentifier("pushNotificationNavigation") as! UINavigationController
let dVC:NotTestViewController = navigationController.topViewController as! NotTestViewController
// This is for passing the URL to the view Controller
dVC.url = self.url!
self.window?.rootViewController?.presentViewController(navigationController, animated: true, completion: {})

})
)
alertCtrl.addAction(UIAlertAction(title: "Cancelar", style: .Destructive, handler: nil))
}
// Find the presented VC...
var presentedVC = self.window?.rootViewController
while (presentedVC!.presentedViewController != nil) {
presentedVC = presentedVC!.presentedViewController
}
presentedVC!.presentViewController(alertCtrl, animated: true, completion: nil)

handler(UIBackgroundFetchResult.NoData)
}


Related Topics



Leave a reply



Submit