使用EKEventEditViewController创建带闹钟的日历事件

时间:2011-10-12 15:47:52

标签: iphone ios events alarm

我正在使用以下代码创建一个事件,并显示一个弹出窗口,要求用户保存该事件:

EKEventStore *eventStore = [[EKEventStore alloc] init];
EKCalendar *calendar = [eventStore defaultCalendarForNewEvents];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.calendar = calendar;
event.title = [NSString stringWithFormat:@"Event: %@", [self.event title]]; 
event.location = self.event.location;
event.notes = [self stringByStrippingHTML: [self.event description]];
event.startDate = [self.event startDate]; 
event.endDate = [self.event endDate];

NSTimeInterval alarmOffset = -1*60*60;//1 hour
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:alarmOffset];

[event addAlarm:alarm];
EKEventEditViewController *eventViewController = [[EKEventEditViewController alloc] init];
eventViewController.event = event;
eventViewController.eventStore=eventStore;
eventViewController.editViewDelegate = self;
[self.navigationController presentModalViewController:eventViewController animated:YES];

这项工作正常,但事件警报属性未设置,因为您可以从下面的图像中看到:

Alarm Not Set

如果我在显示视图控制器之前保存了该事件,它确实会设置警报。

请注意我正在使用LLVM编译器,所以不要担心不发布内容!

TA

罗斯

2 个答案:

答案 0 :(得分:4)

终于找到了怎么做。

您的控制器必须实现协议UINavigationControllerDelegate,并将EKEventEditViewController委托设置为self。然后只需实现

navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

方法并在那里添加警报。

这是我的实施。

- (void)navigationController:(UINavigationController *)navigationController 
  willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    if ([navigationController isKindOfClass:[EKEventEditViewController class]]) {
      EKEventEditViewController *ek = (EKEventEditViewController*)navigationController;
      EKEvent *event = ek.event;
      // set alarm to 15 mins prior of the event if it starts later than 15 mins out
      if ([event.startDate compare:[[NSDate date] dateByAddingTimeInterval:60*15]] != NSOrderedAscending) { 
        EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:60*15*-1];
        event.alarms = [NSArray arrayWithObject:alarm];
      }    
    }
}

答案 1 :(得分:4)

NSTimeInterval alarmOffset = -1*60*60;//1 hour
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:alarmOffset];

[event addAlarm:alarm];

在呈现控制器之后,即在行

之后写上面的代码
[self.navigationController presentModalViewController:eventViewController animated:YES];