IOS Overriding Local Notifications

2019-03-06 18:04发布

问题:

I created a Local Notification that triggers 60 seconds when a certain button(SetButton) is clicked. My problem right now is if SetButton is pressed again, it does not override the first press, it displays 2 notifications and so on. How do I make sure that the second press of the button overrides the first press and there isn't a build up of notifications ?

- (IBAction)SetButtonPressed:(id)sender {
      UILocalNotification *localNotification = [[UILocalNotification alloc] init];
      localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
      localNotification.alertBody = @"HEY GET UP";
      localNotification.timeZone = [NSTimeZone defaultTimeZone];
      localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

}

My AppDelegate.m

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
     if ([UIApplication instanceMethodForSelector: @selector(registerUserNotificationSettings:)]) {
         [application registerUserNotificationSettings: [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
     }

     if (localNotification) {
        application.applicationIconBadgeNumber = 0;
     }
}

回答1:

If you only use notifications for that specific action you could cancel all notifications at once using

[[UIApplication sharedApplication] cancelAllLocalNotifications];


回答2:

It looks like you only have one type of local notifications in your app.

In that case you could keep it simple. Whenever you want to schedule a new one - cancel the previous one.

- (IBAction)SetButtonPressed:(id)sender {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
    localNotification.alertBody = @"HEY GET UP";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.applicationIconBadgeNumber = 
      [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
}