【发布时间】:2014-09-17 21:55:34
【问题描述】:
在我的应用程序中,我有几行代码准备早上 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];
}
在我的应用程序WillEnterForeground 中:
UIApplication *app = [UIApplication sharedApplication];
NSArray *oldNotifications = [app scheduledLocalNotifications];
if ([oldNotifications count] > 0) {
[app cancelAllLocalNotifications];
}
我认为问题在于 [oldNotifications 计数]。在实施 NSLog 以检查它的数量后,它每次显示为 0。这应该算上,对吧? 有什么帮助??? :)
【问题讨论】:
-
当前时间是早上 7 点之后吗?也许你的意思是明天早上 7 点?
-
是的,当前时间是早上 7 点之后。我不是说明天,我希望它显示一个通知。每天7点
-
所以,假设现在是上午 10 点。您正在创建 3 小时前的通知。您需要在未来 21 小时内创建它。
-
我希望我的应用每天早上 7 点显示本地通知。问题是每次我在过去的时间后关闭应用程序时,它都会再次显示。我只希望这种情况每天发生一次。
标签: xcode time notifications local nscalendar