2013-05-21 32 views
1

美好的一天! 我使用功能「通過UIActivityItems將事件保存到日曆」。在該功能中,我創建了新日曆並將事件添加到此日曆中:檢查EKCalendar

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. 

而且它的工作。但是,下次每次都會再次創建名稱爲「新日曆」的新日曆。我如何檢查具有該名稱的日曆是否已經存在?我怎樣才能改變日曆的類型?在生日或其他時間

回答

3

首先,您需要使用EventStore的單個實例來生活您的應用,according to Apple

因此,我建議把eventStore您的視圖控制器的屬性:

@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. 
}