Search code examples
iosobjective-cpush-notificationuinavigationcontrollerstoryboard

Push View Controller When Notification Is Tapped


I have a Storyboard app with a UINavigationController as its Storyboard Entry Point. Its normal main view is a ViewController called "ViewController". What I want to have happen is push the controller named "JustNotifications" when a user taps the incoming notification. However, nothing happens as of now. What am I missing?

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSDictionary *notificationData = response.notification.request.content.userInfo;
    
    // Extract data from the notification payload
    NSString *title = notificationData[@"title"];
    NSString *description = notificationData[@"description"];

    // Get a reference to the navigation controller
    UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;

    // Find the currently visible view controller in the navigation stack
    UIViewController *currentViewController = navigationController.visibleViewController;

    // Perform the segue
    [currentViewController performSegueWithIdentifier:@"ShowJustNotificationsSegue" sender:self];

    // Call the completion handler
    completionHandler();
}

Solution

  • - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSDictionary *notificationData = response.notification.request.content.userInfo;
        
        NSString *title = notificationData[@"title"];
        NSString *description = notificationData[@"description"];
        
        // Instantiate the JustNotifications view controller
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        JustNotifications *newViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"JustNotifications"];
        newViewController.titleText = title;
        newViewController.descriptionText = description;
        
        // Wrap the JustNotifications view controller in a new navigation controller
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:newViewController];
        
        // Present the navigation controller modally
        UIViewController *rootViewController = UIApplication.sharedApplication.keyWindow.rootViewController;
        [rootViewController presentViewController:navController animated:YES completion:nil];
        
        completionHandler();
    }