如果时间过去,UILocalnotification直接触发

时间:2013-06-19 18:37:32

标签: ios objective-c uilocalnotification

我已经为我的项目添加了几个UILocalnotifications,确切地说是24。 这些通知都看起来像这样

NSTimeInterval timeAdjustment = [[NSDate date] timeIntervalSinceDate:[NSDate networkDate]];
        NSDate *date = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *dateComponents = [calendar components:
                                            (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
                                             NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
                                                       fromDate:date];

NSDateComponents *comps = [[NSDateComponents alloc] init];
            [comps setDay:[dateComponents day]];
            [comps setMonth:[dateComponents month]];
            [comps setYear:[dateComponents year]];
            [comps setHour:18];
            [comps setMinute:25];
            NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
            NSDate *fireDate = [gregorian dateFromComponents:comps];
            UILocalNotification *alarm = [[UILocalNotification alloc] init];
            alarm.fireDate = [fireDate dateByAddingTimeInterval:timeAdjustment];
            alarm.soundName = @".aiff";
            alarm.alertBody = @"..";
            alarm.timeZone = [NSTimeZone defaultTimeZone];
            [[UIApplication sharedApplication] scheduleLocalNotification:alarm];

            NSDateComponents *comps2 = [[NSDateComponents alloc] init];
            [comps2 setDay:[dateComponents day]];
            [comps2 setMonth:[dateComponents month]];
            [comps2 setYear:[dateComponents year]];
            [comps2 setHour:18];
            [comps2 setMinute:30];
            NSCalendar *gregorian2 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
            NSDate *fireDate2 = [gregorian2 dateFromComponents:comps2];
            UILocalNotification *alarm2 = [[UILocalNotification alloc] init];
            alarm2.fireDate = [fireDate2 dateByAddingTimeInterval:timeAdjustment];
            alarm2.soundName = @".aiff";
            alarm2.alertBody = @"..";
            alarm2.timeZone = [NSTimeZone defaultTimeZone];
            [[UIApplication sharedApplication] scheduleLocalNotification:alarm2];

所有这些通知都会在正确的时间触发,但问题是如果通知时间过后通知会立即启动。例如,现在它是20.35,通知时间分别是18.25和18.30,但它们现在仍然启动。 我怎么能阻止这个?设置alarm.repeatInterval = NSDayCalendarUnit;不是一个选项,因为我不想要这个。

1 个答案:

答案 0 :(得分:1)

如果当前时间超过您为通知设置的时间,请不要安排通知:

if ([alarm.fireDate compare:[NSDate date]] == NSOrderedDescending) {
    [[UIApplication sharedApplication] scheduleLocalNotification:alarm];
}