Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I create a new EKCalendar on iOS device?

I have an app where I want to schedule some events. So I want to create a new calendar for my app if it does not yet exist and if it does reference that when adding new events.

like image 538
Slee Avatar asked Nov 24 '11 17:11

Slee


People also ask

Can I have two separate Calendars on my iPhone?

From your iPhone or iPad open your Calendar app. Click Calendars at the bottom Page 3 ● Click on the Calendars you would like to view. Choosing multiple will overlay them in the Calendar app with colors matching the choices. You can even choose Show All Calendars from the top.


1 Answers

This is how it is done on iOS 5 using the EventKit framework:

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

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

Now you need to find the local calendar source, if you want the calendar to be stored locally. There are also sources for exchange 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's the part where you can fetch your previously created calendar. When the calendar is created (see below) there is an ID. This identifier has to be stored after creating the calendar so that your app can identify the calendar again. In this example I just stored the identifier in a constant:

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

Now, if you don't have an identifier yet, you need to create the 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 configure properties like the calendar color etc. The important part is to store the identifier for later use. On the other hand if you already have the identifier, you can just fetch the calendar:

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

I put in some debug output as well:

NSLog(@"%@", cal);

Now you either way have a EKCalendar object for further use.

EDIT: As of iOS 6 calendarWithEventStore is depreciated, use:

cal = [EKCalendar calendarForEntityType:<#(EKEntityType)#> eventStore:<#(EKEventStore *)#>];
like image 124
Dennis Bliefernicht Avatar answered Oct 06 '22 13:10

Dennis Bliefernicht