iOS在特定日期设置本地通知

时间:2013-10-09 15:32:47

标签: ios objective-c uilocalnotification

我确信这个问题在某处重复,但我找不到解决方案。我正在创建一个应用程序,其中一个功能允许用户选择他们将收到本地通知的日期和时间。

他们可以选择他们喜欢的一天中的任何时间,并可以切换一周中的不同日期(周一,周二,妻子等)。通知将每周发送一次。因此,我限制用户只创建3个通知 - 如果选择了所有7天,我会将repeatInterval设置为每日(一个通知)。如果为每3个通知选择了6天,那么我将需要每天的单独通知(总共3x6 = 18个通知)。很可能只会使用1个通知,所以这很好。

我知道如何在将来的某个时间设置通知,但如何在星期一下午6点设置通知?

以下是我用于测试的代码。它将来会设置4秒的警报(我是从applicationDidEnterBackground调用它。)

    NSDateComponents *changeComponent = [[NSDateComponents alloc] init];
    changeComponent.second = 4;

    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDate *itemDate = [theCalendar dateByAddingComponents:changeComponent toDate:[NSDate date] options:0];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    localNotif.fireDate = itemDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    localNotif.repeatInterval = NSWeekdayCalendarUnit;

4 个答案:

答案 0 :(得分:3)

与您现在正在做的完全相同,但以不同方式创建日期:

NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:2013];
[comps setHour:10];
[comps setMinute:10];
[comps setSecond:10];
localNotif.fireDate = [[NSCalendar currentCalendar] dateFromComponents:comps];

答案 1 :(得分:3)

我也搜索过它。下面的代码对我有用。将星期日值1到7星期日到星期六和通知机构通过您要触发的操作并指定您的日期然后通知将在特定日期到来。希望这对您有所帮助。

-(void) weekEndNotificationOnWeekday: (int)weekday :(UILocalNotification *)notification : (NSDate*) alramDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: alramDate];
    [componentsForFireDate setWeekday: weekday] ; //for fixing Sunday
  //   [componentsForFireDate setHour: 20] ; //for fixing 8PM hour
 //    [componentsForFireDate setMinute:0] ;
 //    [componentsForFireDate setSecond:0] ;
    notification.repeatInterval = NSWeekCalendarUnit;
    notification.fireDate=[calendar dateFromComponents:componentsForFireDate];
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

}

答案 2 :(得分:1)

  

我知道如何在将来的某个时间设置通知,   但是如何在星期一下午6点设置通知?

您可以在How to Get an NSDate for a Specific Day of Week and Time from an Existing NSDate显示下一个星期一下午6点创建一个NSDate对象。然后,如果您希望它在每个星期一重复,您可以使用localNotification.repeatInterval = NSWeekCalendarUnit。但是我不确定它会在夏令时期间按预期工作。

答案 3 :(得分:0)

我认为您无法安排具有这么大灵活性的通知。只要在他们改变它的时候安排下一个,并且当它触发计划时,下一个即将发生。只有一个人担心取消并且易于设置。