注意:下面有更新。
我在上一个问题中询问过如何为每小时重复间隔指定一分钟。但是,我有两个答案要求我尝试使用日期组件,我做到了。这里是:
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
NSDateComponents *componentsForReferenceDate = [[NSDateComponents alloc] init];
[componentsForReferenceDate setHour:hour];
[componentsForReferenceDate setMinute:0];
[componentsForReferenceDate setSecond:0];
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForReferenceDate];
// Create the notification
UILocalNotification *notification = [[UILocalNotification alloc] init] ;
notification.fireDate = fireDateOfNotification;
notification.timeZone = [NSTimeZone localTimeZone] ;
notification.alertBody = [NSString stringWithFormat: @"You are missed!"] ;
notification.alertAction = @"View";
notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Some information"] forKey:@"information"];
notification.repeatInterval= NSHourCalendarUnit ;
notification.soundName = @"Appnotifisound.wav";
notification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:notification] ;
该代码在我看来是正确的,它应该像我被告知它应该在每小时开始时触发一个通知一样工作。然而,事实并非如此!代码是完整的,我已经设置了属性并正确地合成了它,即使 NSCalendar 在那里。它可以完美地构建和运行,但是,它永远不会在我的模拟器上每小时触发一次通知!?我只是无法理解似乎有什么问题。如果您需要更多信息或复制代码的其他部分以帮助我查找缺少的内容,请告诉我。谢谢你。
更新:如果可能是问题,这是我对小时进行编码的方式..
NSCalendar *calendar1 = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar1 components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
hour = [components hour];
min =[components minute];
sec =[components second];
NSLog(@"hour is %i",hour);
NSLog(@"min is %i",min);
NSLog(@"sec is %i",sec);
if (hour < 24) {
hour=hour+1;
} else {
hour=0;