【问题标题】:EventKit created and make a defaultCalendar automaticEventKit 创建并自动生成一个 defaultCalendar
【发布时间】:2025-12-29 09:55:11
【问题描述】:

我正在使用 eventkit 为大学制作一个应用程序。我正在尝试创建一个日历并使他像一个“defaultCalendar,自动”,仅在此日历上添加和阅读所有事件。

我的代码是:

//我打电话来制作这段代码

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

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

    EKCalendar *cal;
    cal = [EKCalendar calendarWithEventStore:store];

    cal.title = @"NewCalendar";
    cal.source = localSource;
    [store saveCalendar:cal commit:YES error:nil];


    //self.appDelegate.eventManager.selectedCalendarIdentifier = cal.calendarIdentifier;
    //  [cal.calendarIdentifier=cal.calendarIdentifier];


    [[NSUserDefaults standardUserDefaults] setObject:cal.calendarIdentifier forKey:@"NewCalendar"];

}

}

所以问题是我怎样才能创建这个日历,并且只在我的应用程序上使用这个日历。 谢谢

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    您只需要创建日历并将其标识符存储在 NSUserDefaults 中。获得标识符后,您始终可以在应用程序中使用该日历。您的代码已经创建了日历cal。从那里,首先,在 NSUserDefaults 中创建一个键,以便您可以存储它的标识符

    NSString *defaultCalendarIdentifier = [[NSUserDefaults standardUserDefaults] stringForKey:@"defaultCalendarIdentifier"];
    

    然后您可以将日历标识符存储为您刚刚创建的键的值。

    [[NSUserDefaults standardUserDefaults] setObject: [eventStore cal].calendarIdentifier forKey:@"defaultCalendarIdentifier"];
    

    NSUserDefaults 将保存日历 ID,即使在用户关闭并重新打开应用程序之后也是如此。

    当您从该日历创建和读取事件时,请始终使用您刚刚存储的日历 ID 执行此操作。

    EKEvent *event = [EKEvent eventWithEventStore:eventStore];
    //get default Calendar Identifier
    NSString *defaultCalendarIdentifier = [[NSUserDefaults standardUserDefaults]
                            stringForKey:@"defaultCalendarIdentifier"];
    event.calendar = [eventStore calendarWithIdentifier:defaultCalendarIdentifier
    

    这基本上是您创建日历并在应用程序中使用它的方式。

    【讨论】:

    • 非常感谢您的回答:)
    最近更新 更多