2012-01-29 48 views
0

我正在制作闹钟应用程序,该应用程序在特定用户选定日期触发本地通知,即如果用户选择了M,F,Sat,则应在每M/F/Sat时触发闹钟只要。我的问题是,当时我的血腥警报正在发射。我如何限制它到用户选定的日子?这里是我的代码如何在特定日期获得UILocalNotification重复

//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; 
    [email protected]"alarm-clock-ringing-01.wav"; 

    [[UIApplication sharedApplication] scheduleLocalNotification:notification] ; 
+0

由于某种原因我的日期出来错了,即当我做NSLog现在:2012-01-29 22:00:37 +0000 fireDateOfNotification:2012-01-01 21:58:00 +0000 – 2012-01-29 22:06:20

+0

你解决了你的问题吗? – chancyWu 2014-01-23 08:34:40

回答

0

你可以使三个闹钟:一个最接近的周一,周三最接近和最亲密的周五和他们每个人的设置notification.repeatInterval = NSWeekCalendarUnit

+0

我试过NSWeekCalendarUnit它仍然每天都会发出警报,即它现在正在发射,即使它的星期日 – 2012-01-29 22:03:12

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将执行指定的单元相同的动作(在这种情况下,“天“,将重复每一天,不管你指定的通知日期)