-->

UILocalNotification fire when i open the notificat

2020-07-20 03:55发布

问题:

i used the local notification and schedule the fire date but when the app is in background and i open the notification tray to see the notification then the local notification is fire automatically but the fire date is remaining..is there any solution to solve that problem

回答1:

This sounds like you have two issues. First, the local notification has been created with a fire date set in the past - that's why its appearing as soon as you open the app.

Secondly, you may be setting the notification's repeatInterval to a non-zero value, which will cause it to come up more than once.

See the below code for setting a local notification to fire at 3pm:

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = @"This is a test alert";
NSCalendar *currentCalendar = [NSCalendar currentCalendar];

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour: 15];
[comps setMinute: 0];
[comps setSecond: 0];
NSDate *threePM = [currentCalendar dateFromComponents:comps];

// Test if the current time is after three or not:
if(threePM != [threePM earlierDate: [NSDate date]])
{
  comps = [[NSDateComponents alloc] init];
  [comps setDay: 1];
  threePM = [currentCalendar dateByAddingComponents: comps toDate: threePM options: 0];
}

localNotification.fireDate = threePM;
localNotification.repeatInterval = 0;

[[UIApplication sharedApplication] scheduleLocalNotification: localNotification];