Search code examples
iosxcodeuiviewcontrolleruilocalnotificationuiwindow

How can I show a modal view in response to a notification as a new window? (no parent vc)


I am having a lot of issues handling my incoming local notifications. My app is using storyboards and has a tabbarcontroller as the rootviewcontroller. Currently I launch the modalviews from 'didReceiveLocalNotification' in the following manner:

MedicationReminderViewController *vc = [[MedicationReminderViewController alloc] initWithNibName:@"MedicationReminderViewController" bundle:nil];
    vc.notificationInfo = [[NSDictionary alloc] initWithDictionary:notification.userInfo];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc];
    navController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    navController.title = @"title";

    UITabBarController *tc = (UITabBarController *)self.window.rootViewController;
    UINavigationController *nc = (UINavigationController *)tc.selectedViewController;    
    [[nc visibleViewController] presentModalViewController:navController animated:YES];

This works but not on all occasions. I'd like to present the modal view in a new window over anything else that could be displayed at that time. When the user handles the incoming notification the modal view will dismiss itself and the underlying view that was active before the notification came in will be visible again. How can I achieve this?


Solution

  • Do it in your AppDelegate on the window object. I believe you could do it there. From the top of my head, I believe its the window.rootViewController. Unsure though.

    How to do it: When you recieve your UILocalNotification, you can recieve it in the AppDelegate. When the notification "arrives", use the presentModalViewController on self.window.rootViewController.

    update
    From the doc:

    If the application is foremost and visible when the system delivers the notification, no alert is shown, no icon is badged, and no sound is played. However, the application:didReceiveLocalNotification: is called if the application delegate implements it. The UILocalNotification instance is passed into this method, and the delegate can check its properties or access any custom data from the userInfo dictionary.

    Use the application:didReceiveLocalNotification: method. I hope that answered your question.