How to create a new EKCalendar on an iOS device?

I have an application where I want to schedule some events. Therefore, I want to create a new calendar for my application if it does not already exist, and if it refers to this when adding new events.

+13
source share
1 answer

Here's how to do it on iOS 5 using the EventKit framework:

First of all, you need an EKEventStore object to access all:

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

Now you need to find the source of the local calendar if you want the calendar to be stored locally. There are also sources for the exchange of accounts, CALDAV, MobileMe, etc.:

 // find local source EKSource *localSource = nil; for (EKSource *source in store.sources) if (source.sourceType == EKSourceTypeLocal) { localSource = source; break; } 

Now here is the part where you can get your previously created calendar. When the calendar is created (see below), there is an identifier. This identifier must be saved after creating the calendar so that your application can identify the calendar again. In this example, I just saved the identifier in a constant:

 NSString *identifier = @"E187D61E-D5B1-4A92-ADE0-6FC2B3AF424F"; 

Now, if you do not have an identifier yet, you need to create a calendar:

 EKCalendar *cal; if (identifier == nil) { cal = [EKCalendar calendarWithEventStore:store]; cal.title = @"Demo calendar"; cal.source = localSource; [store saveCalendar:cal commit:YES error:nil]; NSLog(@"cal id = %@", cal.calendarIdentifier); } 

You can also set properties such as calendar color, etc. The important part is to keep the identifier for later use. On the other hand, if you already have an identifier, you can simply select the calendar:

 else { cal = [store calendarWithIdentifier:identifier]; } 

I also added some debugging results:

 NSLog(@"%@", cal); 

Now, in any case, you have an EKCalendar object for future reference.

EDIT: As of iOS 6, calendarWithEventStore depreciating, use:

 cal = [EKCalendar calendarForEntityType:<#(EKEntityType)#> eventStore:<#(EKEventStore *)#>]; 
+27
source

All Articles