Search code examples
iphoneiosnsnotificationuilocalnotification

How to register for an NSNotification from a UILocalNotification?


I have a tabbar application and let's say that I want to switch to the second tab and popup an alert at 12:00, even if my application is not running.

I got all the code for UILocalNotification working correctly, but then I thought that the best way to do that would be by posting a notification from the app delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Add the tab bar controller's view to the window and display.
    [window addSubview:tabBarController.view];
    [window makeKeyAndVisible];

    // Handle launching from a notification when the app is NOT running
    UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotification) {
        [tabBarController setSelectedIndex:1];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AlertNotification" object:self];
    }
    return YES;
}

Then, in my SecondViewController.m, I have:

- (void)viewDidLoad {
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popUpAlert:) name:@"AlertNotification" object:nil];
}

But this does not work. I suspect that the notification is sent while the viewDidLoad of the SecondViewController has not been called yet, right? Is it possible to work this out? And do you agree on my approach of using NSNotificationCenter in this case?

Thanks in advance.


Solution

  • I quickly created a test project and got it working by putting the notification registration in awakeFromNib (assuming SecondViewController is created in a xib file)

    - (void)awakeFromNib {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popUpAlert:) name:@"AlertNotification" object:nil];
    }