2

再会!我通过 UIActivityItems 使用“将事件保存到日历”功能。在该功能中,我创建新日历并将事件添加到此日历:

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

// Get the calendar source
EKSource* localSource;
for (EKSource* source in eventStore.sources) {
    if (source.sourceType == EKSourceTypeLocal)
    {
        localSource = source;
        break;
    }
}

if (!localSource)
    return;

EKCalendar *newCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
calendar.source = localSource;
calendar.title = @"New Calendar";

NSError *errorCalendar;
[eventStore saveCalendar:newCalendar commit:YES error:&errorCalendar]; 

EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
event.title     = @"Title";

event.startDate = startDate;
event.endDate   = endDate;

[event setCalendar:newCalendar];
// and etc.

及其工作。但每次下一次它都会再次创建名为“新日历”的新日历。如何检查具有该名称的日历是否已存在?以及如何更改日历类型?生日等。

4

1 回答 1

4

首先,根据 AppleEventStore的说法,您需要在应用程序的整个生命周期中使用单个实例。

因此,我建议将eventStore您的视图控制器设为 a 属性:

@property (nonatomic, retain) EKEventStore *eventStore;

在你的viewDidLoad:

self.eventStore = [[EKEventStore alloc] init];

eventStore现在,您可以在执行任何操作之前检查正在读取和写入的同一实例:

-(BOOL)checkForCalendar {
    //get an array of the user's calendar using your instance of the eventStore
    NSArray *calendarArray = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];

    // The name of the calendar to check for. You can also save the calendarIdentifier and check for that if you want
    NSString *calNameToCheckFor = @"New Calendar";

    EKCalendar *cal;

    for (int x = 0; x < [calendarArray count]; x++) {

        cal = [calendarArray objectAtIndex:x];
        NSString *calTitle = [cal title];

        // if the calendar is found, return YES
        if (([calTitle isEqualToString:calNameToCheckFor]) {

            return YES;
        }
    }

    // Calendar name was not found, return NO;
    return NO;
}

-(void)saveNewEvent {

    // If the calendar does not already exist, create it before you save the event.
    if ([self checkForCalendar] == NO) { 

        // Get the calendar source
        EKSource* localSource;
        for (EKSource* source in eventStore.sources) {
            if (source.sourceType == EKSourceTypeLocal)
            {
                localSource = source;
                break;
            }
        }

        if (!localSource)
            return;

        EKCalendar *newCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
        calendar.source = localSource;
        calendar.title = @"New Calendar";

        NSError *errorCalendar;
        [eventStore saveCalendar:newCalendar commit:YES error:&errorCalendar];

    } 
        EKEvent *event  = [EKEvent eventWithEventStore:self.eventStore];
        event.title     = @"Title";
        event.startDate = startDate;
        event.endDate   = endDate;
        [event setCalendar:newCalendar];
        // and etc.
}
于 2013-11-19T16:17:00.220 回答