如何以编程方式指定添加日历事件的特定日期和时间

时间:2012-04-01 11:04:46

标签: iphone nsdate icalendar eventkit

我正在尝试以编程方式将事件添加到默认日历中,但无法找到我如何设置事件发生的时间以及事件的持续时间。到目前为止,通过遵循许多不同的教程,我所做的就是创建一个每天重新出现的全天活动。我到目前为止的代码如下。

EKEventStore *eventStore = [[EKEventStore alloc] init];

    EKEvent *event = [EKEvent eventWithEventStore:eventStore];


    // use this in the method that actually creates the event
    NSError *err = nil;
    //This date will be the date our reminder expires, as in stops recurring.  Two years was chosen as most users
    //will replace their device after 2 years
    NSDate *fourteenWeeksFromNow = [NSDate dateWithTimeIntervalSinceNow:8467200];
    //Define the recurrance rule
    EKRecurrenceRule *recurrance;
    NSDateComponents *comp = [[NSDateComponents alloc]init];


    [comp setYear:0];
    [comp setMonth:0];
    [comp setDay:7]; 
    //Recurr every 7 days I think but not working
    recurrance = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:EKRecurrenceFrequencyWeekly interval:1 end:[EKRecurrenceEnd recurrenceEndWithEndDate:fourteenWeeksFromNow]];

    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //Our remind date
    NSDate *eventDate = [cal dateByAddingComponents:comp toDate:[NSDate date] options:0]; // unsure what this does or how to use it


    double alarmAmountInSeconds = 60.0*60.0*0.25; // 15 mins
    EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:(-1.0*alarmAmountInSeconds)]; // this is working correctly, alerts 15 minutes before

    NSMutableArray *alarmsArray = [[NSMutableArray alloc] init];

    [alarmsArray addObject:alarm];


    [recurrenceRules arrayByAddingObject:recurrance];

    event.title = module;

    event.startDate = [[NSDate alloc] init]; //  works
    event.endDate = [[NSDate alloc] initWithTimeInterval:8467200 sinceDate:event.startDate]; // works

    event.calendar = eventStore.defaultCalendarForNewEvents; // works
    event.title = module; // works
    event.allDay = FALSE; // dont want it all day but need to be able find out how to set time
    event.location = @"Test location"; 
    event.alarms = alarmsArray; // works
    event.recurrenceRules = recurrenceRules; // not working could be problems with other attributes though
    event.notes = @"This is a test"; // works


    // Try to save the event
    [eventStore saveEvent:event span:EKSpanFutureEvents error:&err];

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我犯的错误并不是我如何考虑类和类名。我知道这似乎很愚蠢。一切都是在开始和结束日期完成的,我希望看到更多的属性来设置确切的时间。但是现在我看到这是通过获得适当的秒数并使用NSDate来完成的。