19 Feb 2014

UILocalNotification Tutorial: Add and cancel LocalNotifications in iPhone SDK

UILocalNotification IOS

As of iOS4, Apple has introduced a new type of notification that can be scheduled to fire within the device itself. It requires no complicated server programming, or additional configuration with iTunes. I am talking about Local Notifications.Local notifications can be scheduled on the user’s IPhone Device to fire at any given time; you can even set them to be recurring.
To create a local notification, we will use given below code snippet or following steps
From IOS 8 onward you have to ask for UIlocalNotification permission from the user, you can do this by adding below chunk of code in applicationDidFinishLaunching method of AppDelegate.m

if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];


1.Create the localNotification object 

 UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 

2.Set date to fire notification. Here we set it to fire  after 30 seconds

 [localNotification setFireDate:[NSDate dateWithTimeIntervalSinceNow:30]]; 

3.The button's text that launches the application and is shown in the alert

 [localNotification setAlertAction:@"Ok"]; 

4.Set the message in the notification from the textField's text

 [localNotification setAlertBody:@"Notification Alert"]; 

5.Set the Application Icon Badge Number of the application's icon to the current Application Icon Badge Number plus 1

 [localNotification setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber]+1]; 

6.Set sound for notification    

localNotification.soundName=UILocalNotificationDefaultSoundName ;

7.Schedule the notification with the system    

 [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 

8. Release localNotification object

[localNotification release];

To cancel a localnotification in iPhone SDk, one can use


method. To use it write below line of code

[[UIApplication sharedApplication] cancelAllLocalNotifications];

This will remove all local notification registered by your app. 

No comments:

Post a Comment