14.3. Receiving Local Notifications in the Background

Problem

You want to present an alert to your user even when your application is not running. You want to create this alert locally inside your application without using push notifications.

Solution

Instantiate an object of type UILocalNotification and schedule it using the scheduleLocalNotification: instance method of UIApplication:

- (BOOL) localNotificationWithMessage:(NSString *)paramMessage
                    actionButtonTitle:(NSString *)paramActionButtonTitle
                          launchImage:(NSString *)paramLaunchImage
                     applicationBadge:(NSInteger)paramApplicationBadge
                       secondsFromNow:(NSTimeInterval)paramSecondsFromNow
                             userInfo:(NSDictionary *)paramUserInfo{
  
  if ([paramMessage length] == 0){
    return NO;
  }
  
  UILocalNotification *notification = [[UILocalNotification alloc] init];
  notification.alertBody = paramMessage;
  notification.alertAction = paramActionButtonTitle;
  
  if ([paramActionButtonTitle length]> 0){
    /* Make sure we have the action button for the user to press
     to open our application */
    notification.hasAction = YES;
  } else {
    notification.hasAction = NO;
  }
  
  /* Here you have a chance to change the launch image of your application 
   when the notification's action is viewed by the user */
  notification.alertLaunchImage = paramLaunchImage;
  
  /* Change the badge number of the application once the notification is
   presented to the user. Even if the user dismisses the notification, 
   the badge number of the application will change */
  notification.applicationIconBadgeNumber ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.