0

我想在特定的日子设置闹钟。我不明白如何设置kCFCalendarUnitWeekday. 这是我的代码:

NSDateComponents *components = [[NSDateComponents alloc] init];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;
localNotif.fireDate = selected;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatCalendar = [NSCalendar currentCalendar];

if (isSun) {
    [components setWeekday:1];

    [localNotif setRepeatInterval:(NSInteger)components];
}

if (isMon) {
    [components setWeekday:2];
    [localNotif  setRepeatInterval:(NSInteger)components];  
}

谢谢你。

4

1 回答 1

1

好的,这里有一些代码可以让您朝着正确的方向前进:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:[NSDate date]];

    // this will set the weekday to sunday
[components setWeekday:1];
    // this is a new date on sunday
NSDate * newDate = [gregorian dateFromComponents:components];

您仍然必须找出 newDate 是否在过去,因此它不会触发。


您实际上已经准备好代码:

// ... init code ...

// *** this the important date ***
localNotif.fireDate = dateOnASunday;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatCalendar = NSWeekCalendarUnit;

... // add body etc. ...

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

围绕此代码段创建一个方法并使用参数传递日期,以便您可以重用它。你只需要输入一个应该是第一个开火日期的日期,它会每周重复一次。你只需要在星期天或星期三传递一个日期。

您可以像这样设置重复间隔:

// repeats notification on a weekly basis
localNotif.repeatCalendar = NSWeekCalendarUnit;

repeatCalender 属性是NSCalendarUnit类型,它是一个枚举。

于 2011-04-16T08:38:02.697 回答