我遇到了一个奇怪的问题 EKEventStore、iCloud 和本地日历。如果启用了 iCloud,则会创建日历并将事件保存到您所期望的日历中。如果 iCloud 已关闭并且您尝试保存事件,则没有任何反应,但是设备会继续每 3-5 秒循环创建 iCloud 日历,直到重新打开 iCloud,然后所有这些日历作为副本涌入 iCloud。我使用的代码几乎与此处多次引用的代码以及 Apples Docs 中的代码完全相同。我完全不知道为什么它不起作用,而且通常关于 EKEventStore 的文档似乎很少。
//•••••••••••••••••••••••••••••••••••••••••••••• # pragma mark – 保存事件 //•••••••••••••••••••••••••••••••••••••••••• ••••</p>
-(void)saveEventWithDate:(NSDate *)startDate endDate:(NSDate *)endDate
{
AppData *theData = [self theAppData];
if([self checkIsDeviceVersionHigherThanRequiredVersion:@"6.0"]) {
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { // iOS 6 Support
if (granted){
NSLog(@"Access Granted");
} else {
NSLog(@"Access Not Granted");
}
}];
}
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([eventStore calendarWithIdentifier:[defaults objectForKey:@"My Calendar"]] != nil) // Calendar Existed
{
event.calendar = [eventStore calendarWithIdentifier:[defaults objectForKey:@"My Calendar"]];
NSLog(@"Calendar Existed");
} else { // Create Calendar
EKSource *theSource = nil;
for (EKSource* src in eventStore.sources) {
if ([src.title isEqualToString:@"iCloud"]) {
theSource = src;
break;
}
if (src.sourceType == EKSourceTypeLocal && theSource==nil) {
theSource = src;
break;
}
}
[self setupCalendarWithSource:theSource withEvent:event];
}
NSLog(@"Type of Event:%@",typeOfEvent);
if ([typeOfEvent isEqualToString:@"Hello"]) {
event.title = [NSString stringWithFormat:@"%@ Hello",[theData.hello_info objectForKey:@"customer_name"]];
event.location = [NSString stringWithFormat:@"Phone #%@",[theData.hello_info objectForKey:@"customer_phone_number"]];
event.notes = [NSString stringWithFormat:@"Hello Issue: %@",[theData.hello_info objectForKey:@"hello_issue"]];
NSLog(@"Hello");
}
event.startDate = startDate;
event.endDate = endDate;
event.allDay = NO;
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:-1800]; // Half Hour Before
event.alarms = [NSArray arrayWithObject:alarm];
[eventStore saveEvent:event span:EKSpanThisEvent error:nil];
SAFE_PERFORM_WITH_ARG(_delegate, @selector(wasScheduled), nil);
}
-(void)setupCalendarWithSource:(EKSource *)theSource withEvent:(EKEvent *)event {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
EKCalendar *cal;
cal = [EKCalendar calendarWithEventStore:eventStore];
cal.title = @"My Appointments";
cal.source = theSource;
[eventStore saveCalendar:cal commit:YES error:nil];
NSLog(@"cal id = %@", cal.calendarIdentifier);
NSString *calendar_id = cal.calendarIdentifier;
[defaults setObject:calendar_id forKey:@"My Calendar"];
event.calendar = cal;
}