How to react to Local Notifications in your iOS App

Now that we know how to create Local Notifications, let’s see how we can react to them. Say your app wasn’t running, and you wanted to know if it was launched as a result of a notification.

Photo 06-01-2014 13 36 27

In our AppDelegate we are passed a launchOptions dictionary, which will have a UIApplicationLaunchOptionsLocalNotificationKey option that will contain another dictionary we can give our notification. This probably sounds more complicated than it is… basically if this key is nil, then we were not launched as a result of a notification. If it’s not nil, it will contain options from the notification that launched it.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    // see if we've been woken by a notification
    NSDictionary *notificationOptions = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if ([notificationOptions objectForKey:@"message"]) {
        NSLog(@"%@", [notificationOptions objectForKey:@"message"]);
    } else {
        NSLog(@"Haven't been launched as a result of my notification");
    return YES;

When we create our notification we can pass in a userInfo dictionary like so (see previous step for details):

// pass in options to which we can react
notification.userInfo = @{@"message": @"Your Local Notification says hi ;-)"};

Note that when the app is already running, the didFinishLaunching method is not called. So if the app was open in the background this approach won’t work.

To find out if your already running app has been brought into the foreground, you can implement the following delegate method in your AppDelegate. This will be called if a notification was received, and will include the same userInfo dictionary as above:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"This just in: %@", [notification.userInfo objectForKey:@"message"]);

Note that this method will be called every time your app receives a notification, not just when it’s woken from the background.

Leave a Reply