代码之家  ›  专栏  ›  技术社区  ›  Im Batman

停止重复本地通知iOS

  •  0
  • Im Batman  · 技术社区  · 9 年前

    我每隔30秒初始化一次本地通知。一旦用户按下停止本地通知的按钮,我想停止重复。

    问题是我找不到办法。它每30秒重复一次

    这就是我如何设置本地通知

      // Schedule the notification
        UILocalNotification* localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:30];
        localNotification.alertBody = @"Testing Repeating Local Notification";
        localNotification.applicationIconBadgeNumber = 1;
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        localNotification.repeatCalendar = [NSCalendar currentCalendar];
    
        localNotification.repeatInterval = kCFCalendarUnitSecond;
    
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    

    我试过了 [[UIApplication sharedApplication] cancelAllLocalNotifications]; .但它确实有效。

    3 回复  |  直到 9 年前
        1
  •  1
  •   Vishnu gondlekar    9 年前

    你能设定吗 repeatInterval 设置为0。根据文档,如果设置为零,则会触发一次通知。因此,当按下停止按钮时,您可以执行以下操作

    localNotification.repeatInterval = 0;
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
        2
  •  0
  •   Im Batman    9 年前

    我解决了。

    刚刚删除 localNotification.repeatCalendar = [NSCalendar currentCalendar]; 来自上述代码。

        3
  •  0
  •   Jayesh Thanki    9 年前

    当您在应用程序活动状态下收到通知时,可以删除通知。

    就像

    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
    {
        if (application.applicationState == UIApplicationStateActive)
        {
            NSLog(@"Application is active");
    
            /*
            ...
            do some process
            ...
            */
    
            //remove notification
            [application cancelLocalNotification:notification];
        }
        else
        {
            NSLog(@"Application is inactive");
        }
    }