我有一个应用程序,我想在其中安排一些事件。所以我想为我的应用程序创建一个新日历,如果它尚不存在并且它在添加新事件时确实引用了它。
最佳答案
这是在 iOS 5 上使用 EventKit
框架完成的:
首先,您需要一个EKEventStore
对象来访问所有内容:
EKEventStore *store = [[EKEventStore alloc] init];
现在需要找到本地日历源,如果你想让日历存储在本地。还有交换账户、CALDAV、MobileMe 等来源:
// find local source
EKSource *localSource = nil;
for (EKSource *source in store.sources)
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
现在是您可以获取之前创建的日历的部分。创建日历时(见下文)有一个 ID。此标识符必须在创建日历后存储,以便您的应用程序可以再次识别日历。在这个例子中,我只是将标识符存储在一个常量中:
NSString *identifier = @"E187D61E-D5B1-4A92-ADE0-6FC2B3AF424F";
现在,如果您还没有标识符,则需要创建日历:
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);
}
您还可以配置日历颜色等属性。重要的部分是存储标识符以备后用。 另一方面,如果您已经有了标识符,则可以只获取日历:
else
{
cal = [store calendarWithIdentifier:identifier];
}
我也加入了一些调试输出:
NSLog(@"%@", cal);
现在,无论哪种方式,您都有一个 EKCalendar
对象供进一步使用。
编辑:从 iOS 6 开始,calendarWithEventStore
已弃用,请使用:
cal = [EKCalendar calendarForEntityType:<#(EKEntityType)#> eventStore:<#(EKEventStore *)#>];
关于iphone - 如何在 iOS 设备上创建新的 EKCalendar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8260752/