Iphone 如何在iOS设备上创建新日历?

Iphone 如何在iOS设备上创建新日历?,iphone,objective-c,ios,ipad,Iphone,Objective C,Ios,Ipad,我有一个应用程序,我想安排一些活动。因此,如果我的应用程序还不存在,并且在添加新事件时引用了日历,我想为它创建一个新日历。这是在iOS 5上使用EventKit框架完成的: 首先,您需要一个EKEventStore对象来访问所有内容: EKEventStore *store = [[EKEventStore alloc] init]; 现在,如果希望本地存储日历,则需要查找本地日历源。还有外汇账户、CALDAV、MobileMe等来源: // find local source EKSourc

我有一个应用程序,我想安排一些活动。因此,如果我的应用程序还不存在,并且在添加新事件时引用了日历,我想为它创建一个新日历。

这是在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];
}
您还可以配置日历颜色等属性。重要的部分是存储标识符以供以后使用。 另一方面,如果您已经拥有该标识符,则只需获取日历:

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 *)#>];
cal=[EKCalendar calendarForEntityType:eventStore:];

当我尝试创建新日历时,我的日历有时会出现,然后从我的iPad日历应用程序中消失。我希望创建一个新的日历也能将其添加到日历应用程序中。我需要能够查询这些事件,日历分离似乎是最好的方式。看起来是iCloud被打开,这是在删除我的事件,我该怎么办?@matt我看到的是,如果用户有iCloud,如果你创建本地日历,它在iCal中是“不可见”的。但如果他们没有iCloud,它就会如预期的那样出现。因此,我首先检查iCloud,如果可用的话,使用它,否则就在本地创建。Ooops,找到了原因,在苹果的开发者论坛上:我必须关闭iCloud并禁用gmail日历同步。在我这样做之前,本地日历的创建没有发生错误。@DennisBliefernicht for me with EKSourceTypeLocal日历没有显示在日历应用程序中,更改为EKSourceTypeSubscribed修复了这一问题。