iPhone Event Kit : programmatically create a EKCalendar?

前端 未结 3 979
旧时难觅i
旧时难觅i 2020-12-29 14:47

I would like to insert events in my app, so they can be viewed in iPhone Calendar.app. But since I don\'t want to mix the user events with those from my app, I wanted to cre

3条回答
  •  -上瘾入骨i
    2020-12-29 15:30

    This is how you can check out whether a calendar already exists with specific title. If it does not exists then you can create it programatically.

    Declare a Boolean Type Variable

    BOOL doesExist=NO;
      EKEventStore *eventStore=[[EKEventStore alloc] init];
    
      NSArray *calanders=[eventStore   calendarsForEntityType:EKEntityTypeEvent];
    
      //Now Iterate through every calendar in the array and match its title  
      // with the title that you want to create
    
    
    
     for(EKCalendar calendar in calendars)
       {
             if([[calendar title] isEqualToString:@"youdesiredname"])
              {
                       doesExist=YES; 
              }
    
       }
    

    // so now check if our bool variable contains value YES it means that a calendar with same name/title already exists.if no then you can create

     if(!doesExist)
        {
            NSString* calendarName = @"DesiredCalendarName";
            EKCalendar* calendar;
    
    
           EKSource* localSource;
           for (EKSource* source in eventStore.sources) {
           if (source.sourceType == EKSourceTypeLocal)
           {
            localSource = source;
            break;
           }
    
    
    
    
        if (!localSource)
            return;
    
           calendar = [EKCalendar calendarWithEventStore:eventStore];
           calendar.source = localSource;
           calendar.title = calendarName;
    
    
           EKEvent *event = [EKEvent eventWithEventStore:eventStore];
           calendar = [eventStore calendarWithIdentifier:self.calendarIdentifier];
           event.calendar = calendar;
    
          // Set the start date to the current date/time and the event duration to one hour
          NSDate *startDate = [NSDate date];
          event.startDate = startDate;
          event.endDate = [startDate dateByAddingTimeInterval:3600];
    
          //And to save the event to the event database:
    
           NSError *error = nil;
         BOOL result = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
        if (result) 
        {
        NSLog(@"Saved event to event store.")
        } 
       else 
        {
         NSLog(@"Error saving event: %@.", saveError);
        }
    
          NSError* error;
          bool success= [eventStore saveCalendar:calendar commit:YES error:&error];
          if (error != nil)
          {
            NSLog(error.description);
    
          }
    
        }
    

提交回复
热议问题