我正在制作一个闹钟应用程序,用于在某个用户选择的日期触发本地通知,即如果用户选择了M,F,Sat,那么它应该仅在每个M / F / Sat发出警报。我遇到的问题是那时我的血腥警报每天都在开火。如何将其限制为用户选择的日期?这是我的代码
//For testing purposes I want the alarm to fire only on Monday at 7:00am.
//This fires every day at 7:00am
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
// set components for time 7:00 a.m. Monday
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 2] ;
[componentsForFireDate setHour: 7] ;
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
// Create the notification
UILocalNotification *notification = [[UILocalNotification alloc] init] ;
notification.fireDate = fireDateOfNotification ;
notification.timeZone = [NSTimeZone localTimeZone] ;
notification.alertBody = [NSString stringWithFormat: @"Wake up!"] ;
notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Waking Up time"] forKey:@"wakeUp"];
//Problem is here NSDayCalendarUnit makes my alarm fire every day
notification.repeatInterval= NSDayCalendarUnit ;
//notification.soundName=UILocalNotificationDefaultSoundName;
notification.soundName=@"alarm-clock-ringing-01.wav";
[[UIApplication sharedApplication] scheduleLocalNotification:notification] ;
答案 0 :(得分:1)
如果您实际上只启动本地通知一次但是当您的设备收到通知时,它是否会有效,请让它再次发布相同的通知。您的应用无需运行即可运行。
您的应用程序未运行时,您在应用代理的applicationDidFinishLaunching中处理本地通知:
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// handles notification when application is relaunched after being terminated
// not when app is already in the foreground running.
if(localNotif)
{
// repeat the same local notification again
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
注意:repeatInterval将按您指定的单位执行相同的操作(在本例中为“day”,无论您指定的通知日期如何,都会每天重复)
答案 1 :(得分:0)
你可以发出三个警报:一个是最接近的星期一,最接近的星期三和最接近的星期五,并且每个都设置notification.repeatInterval = NSWeekCalendarUnit
。