Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 *)#>];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...