每次播放本地通知都是关闭应用程序

时间:2014-09-17 21:55:34

标签: xcode time notifications local nscalendar

在我的应用程序中,我有几行代码准备早上7点的本地通知。问题是每次关闭应用程序时都会显示通知。我只希望在设定的时间过后发生这种情况。

在我的applicationDidEnterBackground中:

NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date
[components setHour:7];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notifyAlarm = [[UILocalNotification alloc] init];
if (notifyAlarm) {
    notifyAlarm.fireDate = [calendar dateFromComponents:components];
    notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
    notifyAlarm.repeatInterval = 0;
    notifyAlarm.soundName = @"not.wav";
    notifyAlarm.alertBody = @"test";
    [app scheduleLocalNotification:notifyAlarm];
}

在我的applicationWillEnterForeground中:

UIApplication *app = [UIApplication sharedApplication];
    NSArray *oldNotifications = [app scheduledLocalNotifications];
    if ([oldNotifications count] > 0) {
        [app cancelAllLocalNotifications];
    }

我认为问题出在[oldNotifications count]中。在实施了一个NSLog以检查它每次显示的数量0.这应该算起来,对吧? 任何帮助??? :)

1 个答案:

答案 0 :(得分:2)

试试这段代码。如果你想每天重复NSLocalNotification,你需要将repeatInterval设置为NSDayCalender单位。

NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date
[components setHour:7];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notifyAlarm = [[UILocalNotification alloc] init];
if (notifyAlarm)
{
    notifyAlarm.fireDate = [calendar dateFromComponents:components];
    notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
    notifyAlarm.repeatInterval = NSDayCalendarUnit;
    notifyAlarm.soundName = @"not.wav";
    notifyAlarm.alertBody = @"test";
    [app scheduleLocalNotification:notifyAlarm];
}