gpt4 book ai didi

ios - 检查 EKCalendar

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:46:41 26 4
gpt4 key购买 nike

美好的一天!我通过 UIActivityItems 使用函数“将事件保存到日历”。在该函数中,我创建了新日历并将事件添加到该日历:

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

// Get the calendar source
EKSource* localSource;
for (EKSource* source in eventStore.sources) {
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
}

if (!localSource)
return;

EKCalendar *newCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
calendar.source = localSource;
calendar.title = @"New Calendar";

NSError *errorCalendar;
[eventStore saveCalendar:newCalendar commit:YES error:&errorCalendar];

EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = @"Title";

event.startDate = startDate;
event.endDate = endDate;

[event setCalendar:newCalendar];
// and etc.

它的工作原理。但每次下一次它都会再次创建名为“New Calendar”的新日历。如何检查具有该名称的日历是否已存在?以及如何更改日历类型?生日之类的。

最佳答案

首先,您需要在应用的整个生命周期内使用 EventStore 的单个实例,according to Apple .

因此我建议将 eventStore 设为 View Controller 的属性:

@property (nonatomic, retain) EKEventStore *eventStore;

在你的 viewDidLoad:

self.eventStore = [[EKEventStore alloc] init];

现在您可以在执行任何操作之前检查正在读取和写入的同一 eventStore 实例:

-(BOOL)checkForCalendar {
//get an array of the user's calendar using your instance of the eventStore
NSArray *calendarArray = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];

// The name of the calendar to check for. You can also save the calendarIdentifier and check for that if you want
NSString *calNameToCheckFor = @"New Calendar";

EKCalendar *cal;

for (int x = 0; x < [calendarArray count]; x++) {

cal = [calendarArray objectAtIndex:x];
NSString *calTitle = [cal title];

// if the calendar is found, return YES
if (([calTitle isEqualToString:calNameToCheckFor]) {

return YES;
}
}

// Calendar name was not found, return NO;
return NO;
}

-(void)saveNewEvent {

// If the calendar does not already exist, create it before you save the event.
if ([self checkForCalendar] == NO) {

// Get the calendar source
EKSource* localSource;
for (EKSource* source in eventStore.sources) {
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
}

if (!localSource)
return;

EKCalendar *newCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
calendar.source = localSource;
calendar.title = @"New Calendar";

NSError *errorCalendar;
[eventStore saveCalendar:newCalendar commit:YES error:&errorCalendar];

}
EKEvent *event = [EKEvent eventWithEventStore:self.eventStore];
event.title = @"Title";
event.startDate = startDate;
event.endDate = endDate;
[event setCalendar:newCalendar];
// and etc.
}

关于ios - 检查 EKCalendar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com