0

I'm trying to use the iOS 10 UserNotifications framework to do something very basic: open a specific ViewController when the default action is selected. I've been through a number of tutorials but they all focus on custom categories and actions, and they also don't really show the code for launching a specific ViewController after having determined the action (this is simply left as a comment or a print statement).

I want to do one of two things, depending on what is possible:

  1. Instantiate and display a modal ViewController that is not the storyboard's initial view controller, or
  2. display the initial ViewController, but first inject some information into it, such that it can use this information to determine what ViewController to segue to next.

My AppDelegate sets itself as the UNUserNotificationCenterDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Make this object responsible for handling notification events.
    UNUserNotificationCenter.current().delegate = self
    return true
}

And then I want to use the following to override what ViewController is selected:

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

    switch response.actionIdentifier {
    case UNNotificationDismissActionIdentifier:
        // Notification was dismissed. Do nothing.
        completionHandler()
    case UNNotificationDefaultActionIdentifier:
        // App opened from notification.
        // ??? Select ViewController to show based on information found in the notification ???
        completionHandler()
    default:
        completionHandler()
    }
}
Janus Varmarken
  • 2,306
  • 3
  • 20
  • 42
  • You can get the root view controller from the window. So now you can switch to any view controller you want to. – Bhavuk Jain Nov 11 '16 at 17:11
  • @BhavukJain won't that be nil in case my application is being relaunched? – Janus Varmarken Nov 11 '16 at 17:14
  • Before it's even called, did finish launching will be called. So it shouldn't be nil. – Bhavuk Jain Nov 11 '16 at 17:38
  • @BhavukJain Okay, well that's an option that makes item 2 above possible then, but not item1. Also I was hoping to avoid having to down cast an existing view controller, and rather instantiate the one I need on my own. Will the system always instantiate the root view controller when using the default action of a notification? – Janus Varmarken Nov 11 '16 at 19:41
  • No. Why will it instantiate again? You're just taking the reference of the root view controller from the window. – Bhavuk Jain Nov 11 '16 at 19:50
  • @BhavukJain Sorry if I wasn't clear: if possible I would like to bypass the storyboard root view controller and use a different view controller as the root. – Janus Varmarken Nov 11 '16 at 20:00

0 Answers0