本文介绍了每周在特定日期和时间触发通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在每个星期天晚上8点触发 UILocalNotification
,但是,我每天晚上8点都有一个开火日期。
I want to trigger a UILocalNotification
every Sunday at 8PM, however, I'm having a fire date every day at 8PM.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 1] ; //for fixing Sunday
[componentsForFireDate setHour: 20] ; //for fixing 8PM hour
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
UILocalNotification *notification = [[UILocalNotification alloc] init] ;
notification.fireDate = fireDateOfNotification ;
notification.timeZone = [NSTimeZone localTimeZone] ;
notification.alertBody = [NSString stringWithFormat: @"New updates!"] ;
notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"New updates added for that week!"] forKey:@"new"];
notification.repeatInterval= NSDayCalendarUnit ;
notification.soundName=UILocalNotificationDefaultSoundName;
NSLog(@"notification: %@",notification);//it indicates that the notif will be triggered today at 8PM and not Sunday.
[[UIApplication sharedApplication] scheduleLocalNotification:notification] ;
谢谢。
推荐答案
您错过了 NSDateComponents
init函数中的 NSWeekCalendarUnit
。添加 NSWeekCalendarUnit
并将 repeatInterval
设置为 NSWeekCalendarUnit
,然后输出
You missed the NSWeekCalendarUnit
in the NSDateComponents
init function. Add the NSWeekCalendarUnit
to it and set the repeatInterval
to NSWeekCalendarUnit
, then output is
next fire date = Sunday, November 24, 2013 at 8:00:00 PM
代码在这里:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 1] ; //for fixing Sunday
[componentsForFireDate setHour: 20] ; //for fixing 8PM hour
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;
//...
notification.repeatInterval = NSWeekCalendarUnit;
//...
这篇关于每周在特定日期和时间触发通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!