Question

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.

Was it helpful?

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];
}

OTHER TIPS

I guess, you are right. It doesn't work because you are posting the notification before adding the view controller as observer for it.

Another approach would be to add a bool property to the app delegate to indicate whether the app has been started from the local notification. The app delegate can be requested from anywhere in the app with [[UIApplication sharedApplication] delegate].

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
[[UIApplication shareApplication] registerUserNotificationSettings: settings];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top