Open a Viewcontroller from Remote Notification

Open a ViewController from remote notification

I created a sample project with a local notification instead of a remote notification for ease of showing the functionality but it should be as simple as setting the root view controller of the window in the app delegate didreceiveremote notification.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

// Subscribe for notifications - assume the user chose yes for now
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil))

return true
}


func applicationDidEnterBackground(application: UIApplication) {
//Crete a local notification
let notification = UILocalNotification()
notification.alertBody = "This is a fake notification"
notification.fireDate = NSDate(timeIntervalSinceNow: 2)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
let sb = UIStoryboard(name: "Main", bundle: nil)
let otherVC = sb.instantiateViewControllerWithIdentifier("otherVC") as! OtherViewController
window?.rootViewController = otherVC;
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
//Your code here
}

`
You need to worry about managing your view hierarchy and sending anything to it that you need to send from the notification user data.

In my example, I create a local notification when you close the app that fires after a view seconds. If you then launch the app from the notification, it will open the "other view controller" which would be the "SimplePostViewController" in your case.

Also, be sure that you are registering for remote notifications in the didFinishLaunchWithOptions.

Github very simple sample : https://github.com/spt131/exampleNotificationResponse

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 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 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 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 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