IOS local notification: UILocalNotification

Source: Internet
Author: User

I used a small App last year. The key feature was to send a local notification to the user. Unfortunately, I didn't write my blog at the time, so I didn't record the corresponding knowledge. Recently, I encountered the use of this function. This time, I wrote a blog to take notes about UILocalNotification.


First, add a local notification to the system. The Code is as follows:

// Initialize the local notification object UILocalNotification * notification = [[UILocalNotification alloc] init]; if (notification) {// set the notification time NSDate * currentDate = [NSDate date]; notification. timeZone = [NSTimeZone defaultTimeZone]; // use the local time zone notification. fireDate = [currentDate dateByAddingTimeInterval: 5.0]; // set the repetition interval notification. repeatInterval = kCFCalendarUnitDay; // set the notification text content. alertBody = @ "Wake up, man"; notification. alertAction = NSLocalizedString (@ "get up", nil); // use the default notification for notification. soundName = UILocalNotificationDefaultSoundName; // set the notification count in the upper-right corner of the application. applicationIconBadgeNumber ++; // sets the userInfo of the notification to identify the notification NSMutableDictionary * aUserInfo = [[NSMutableDictionary alloc] init]; aUserInfo [kLocalNotificationID] = @ "LocalNotificationID"; notification. userInfo = aUserInfo; // Add the notification to the system [[UIApplication sharedApplication] scheduleLocalNotification: notification];}

The above alertBody is the main text content when the device receives a local notification or when the screen is locked. alertActions is the text content behind the slide to displayed when the screen is locked. For example:



RepeatInterval indicates the notification repetition interval, which is defined in the SDK as follows:

<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;"> @ property (nonatomic) NSCalendarUnit repeatInterval; // 0 means don't repeat
The main values include:

        NSCalendarUnitEra                = kCFCalendarUnitEra,        NSCalendarUnitYear               = kCFCalendarUnitYear,        NSCalendarUnitMonth              = kCFCalendarUnitMonth,        NSCalendarUnitDay                = kCFCalendarUnitDay,        NSCalendarUnitHour               = kCFCalendarUnitHour,        NSCalendarUnitMinute             = kCFCalendarUnitMinute,        NSCalendarUnitSecond             = kCFCalendarUnitSecond,        NSCalendarUnitWeekday            = kCFCalendarUnitWeekday,        NSCalendarUnitWeekdayOrdinal     = kCFCalendarUnitWeekdayOrdinal,

Represents a century, a year, a month, and so on. 0 indicates no repetition. For more information, see CFCalendar Reference.

The lower limit of repeatInterval should be NSCalendarUnitMinute, that is, a duplicate notification is sent every minute.

If it is set to NSCalendarUnitSecond, the message will not be duplicated, and a notification will be sent once per second. Of course, the iOS system will not allow such a message to exist.

It is not good to say that the value cannot be customized (unfortunately, NSCalendarUnit is an enumeration type). For example, you cannot add a 10.0 number to it and want it to be repeated every 10 seconds. Therefore, if you want to send a notification every 20 minutes and send it three times in an hour, you can only set three notifications at the same time.



After the above Code is run, a local notification will be received in five seconds.

After receiving the notification, call the following methods in the program delegate for processing:

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{    NSLog(@"Application did receive local notifications");        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"welcome" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];    [alert show];}

Note that this method is executed only after the program is started. Therefore, this method is not executed when the program is in the background.


Note that if the local notifications sent by our application to the system are periodic, even if the program is deleted and reinstalled, the previous local notifications still exist (not removed from the system) during reinstallation ). For example, we start the method of adding local notifications in the viewDidLoad method, run several times more, delete the program in the simulator, run again, and output all local notifications using the following methods:

    NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];    NSLog(@"%@", localNotifications);

Console output:

2014-03-14 15:46:37.145 LocalNotificationDemo[4419:60b] (    "
 
  {fire date = Friday, March 14, 2014 at 3:38:16 PM China Standard Time, time zone = Asia/Chongqing (GMT+8) offset 28800, repeat interval = NSDayCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, March 15, 2014 at 3:38:16 PM China Standard Time, user info = {\n    ClockID = LocalNotificationID;\n}}",    "
  
   {fire date = Friday, March 14, 2014 at 3:44:45 PM China Standard Time, time zone = Asia/Chongqing (GMT+8) offset 28800, repeat interval = NSDayCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, March 15, 2014 at 3:44:45 PM China Standard Time, user info = {\n    ClockID = LocalNotificationID;\n}}",    "
   
    {fire date = Friday, March 14, 2014 at 3:44:55 PM China Standard Time, time zone = Asia/Chongqing (GMT+8) offset 28800, repeat interval = NSDayCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, March 15, 2014 at 3:44:55 PM China Standard Time, user info = {\n    ClockID = LocalNotificationID;\n}}",    "
    
     {fire date = Friday, March 14, 2014 at 3:45:13 PM China Standard Time, time zone = Asia/Chongqing (GMT+8) offset 28800, repeat interval = NSDayCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, March 15, 2014 at 3:45:13 PM China Standard Time, user info = {\n    ClockID = LocalNotificationID;\n}}",    "
     
      {fire date = Friday, March 14, 2014 at 3:45:29 PM China Standard Time, time zone = Asia/Chongqing (GMT+8) offset 28800, repeat interval = NSDayCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, March 15, 2014 at 3:45:29 PM China Standard Time, user info = {\n    ClockID = LocalNotificationID;\n}}",    "
      
       {fire date = Friday, March 14, 2014 at 3:46:28 PM China Standard Time, time zone = Asia/Chongqing (GMT+8) offset 28800, repeat interval = NSDayCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, March 15, 2014 at 3:46:28 PM China Standard Time, user info = {\n ClockID = LocalNotificationID;\n}}")
      
     
    
   
  
 

We can see that the local notifications sent previously have been stuck in the system.

This is not just a simulator, but also on iOS devices. The previous local notifications will be sent when the previous App reinstalls the device.

Therefore, we need to cancel the notification method. Of course, this object will also be removed from the scheduledlocalconfigurications array.

There are two types of cancellation methods.

The first type is violent. Directly cancel all local notifications:

[[UIApplication sharedApplication] cancelAllLocalNotifications];

This method is applicable when the App is started for the first time during App Reinstallation, or when the restoration program is set by default.

The second method is for a specific notification:

- (void)cancelLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0);

In this case, we need to identify the notification so that we can locate the notification. It can be specified in the userInfo (a dictionary) of notification.

For example:

-(Void) application :( UIApplication *) application didReceiveLocalNotification :( UILocalNotification *) notification {NSLog (@ "Application did receive local communications "); // cancel a specific local notification for (UILocalNotification * noti in [[UIApplication sharedApplication] scheduledlocalconfigurications]) {NSString * notiID = noti. userInfo [kLocalNotificationID]; NSString * required enotiid = notification. userInfo [kLocalNotificationID]; if ([notiID isEqualToString: incluenotiid]) {[[UIApplication sharedApplication] cancelLocalNotification: notification]; return ;}} UIAlertView * alert = [externalloc] initWithTitle: @ "Hello" message: @ "welcome" delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alert show];}


In the end, we recommend that you do not send local notifications too frequently. Otherwise, users will feel very annoyed.



References:

IOS local notification

CFCalendar Reference

IOS: enum, NS_ENUM, NS_OPTIONS







Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.