IOS Overriding Local Notifications

别说谁变了你拦得住时间么 提交于 2019-12-20 07:39:47

问题


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;
}


来源:https://stackoverflow.com/questions/41768568/ios-overriding-local-notifications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!