【问题标题】:Cancel all notifications at specific time在特定时间取消所有通知
【发布时间】:2012-11-26 10:07:10
【问题描述】:

对于我的应用,我不希望通知在周末关闭。 所以我的想法是在星期五的特定时间取消所有通知,我想通过安排任务来做到这一点,就像我安排通知一样(UILocalNotifications

例如,我的闹钟有以下代码:

NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setHour:8];
    [comps setMinute:25];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *fireDate = [gregorian dateFromComponents:comps];

    UILocalNotification *alarm = [[UILocalNotification alloc] init];

    alarm.fireDate = fireDate;
    alarm.repeatInterval = NSDayCalendarUnit;
    alarm.soundName = @"sound.aiff";
    alarm.alertBody = @"Message..";
    alarm.timeZone = [NSTimeZone defaultTimeZone];
    [[UIApplication sharedApplication] scheduleLocalNotification:alarm];

有没有办法用同样的方法取消所有通知,还是苹果不允许这样做?

【问题讨论】:

    标签: iphone objective-c ios uilocalnotification nsdatecomponents


    【解决方案1】:

    您可以通过以下方式取消本地通知:

    [[UIApplication sharedApplication] cancelLocalNotification:notification];
    

    您需要遍历所有本地通知并在周末取消它们。循环遍历它们:

    NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
    [notifications enumerateObjectsUsingBlock:^(UILocalNotification *notification, NSUInteger idx, BOOL *stop){
        if (/* notification.fireDate is on weekend */) {
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
        }
    }];
    

    但是,您必须确保应用在星期五运行才能执行代码以删除周末通知。

    但是,为什么不一开始就安排在周末呢?

    【讨论】:

    • 抱歉,可能不够清楚,我希望通知仅在工作日显示,我无法每天安排它们,因为据我所知,Apple 限制为 64 条通知。该应用程序将在星期五运行(这是我们业务的应用程序) 我想使用 cancelLocalNotification 功能在特定时间关闭,就像我在特定时间安排通知一样,可以吗?
    • 如果有要取消的通知,为什么不在您的应用程序中设置一些每隔一小时左右检查一次的东西。我还是不太明白为什么你不能不安排周末的通知?
    【解决方案2】:

    您可以通过该方法取消所有本地通知

    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    

    如果您想浏览它们,并可能发布最重要的通知,您可以使用scheduledLocalNotifications

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 2015-09-15
      • 2015-02-07
      • 1970-01-01
      • 2018-07-19
      • 2012-12-23
      相关资源
      最近更新 更多