无法在日历中添加事件

Ast*_*pta 4 events calendar objective-c ios

我想在“someName”日历中添加事件。如果不存在具有给定名称的日历,那么我将以编程方式创建一个。我的问题是当 localSource(EKSource 类型)结果为空时,不会添加该事件。我添加了 3 个检查以确保我获得 localSource 的值,但即使在某些情况下 localSource 也是 nil。所以在我的手机上添加了事件,但在我朋友的手机上却没有。

我关注了各种帖子,我了解到 EKSource 可以是 6 种类型:https : //developer.apple.com/reference/eventkit/eksourcetype

我不明白的是在什么情况下 localSource 会为零?这在普通语言中是什么意思?我可以从代码中做一些事情来使它非零还是用户必须在设备上做一些事情?

- (void)setCalendar {
    NSArray *calendars = [self.eventStore calendarsForEntityType:nil];
    NSString *calendarTitle = someName;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title matches %@", calendarTitle];
    NSArray *filtered = [calendars filteredArrayUsingPredicate:predicate];
    if ([filtered count]) {
        self.calendar = [filtered firstObject];
    }
    else {
        self.calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
        self.calendar.title = calendarTitle;
        EKSource *localSource;
        for (EKSource *source in self.eventStore.sources)
        {

            //if iCloud account is setup then add the event in that calendar
            if (source.sourceType == EKSourceTypeCalDAV && [source.title isEqualToString:@"iCloud"])
            {
                localSource = source;
                break;
            }
        }
        if (localSource == nil)
        {
            for (EKSource *source in self.eventStore.sources)
            {
                //if iCloud is not setup then look for local source
                if (source.sourceType == EKSourceTypeLocal)
                {
                    localSource = source;
                    break;
                }
            }

        }
        if (!localSource) {
            localSource = [self.eventStore defaultCalendarForNewEvents].source;
        }
        self.calendar.source = localSource;
        NSError *calendarErr = nil;
        BOOL calendarSuccess = [self.eventStore saveCalendar:self.calendar commit:YES error:&calendarErr];
        if (!calendarSuccess) {
            NSLog(@"Error while updating calendar %@", calendarErr);
        }
    }
Run Code Online (Sandbox Code Playgroud)

}

PS:我有权添加日历事件。

Ast*_*pta 5

本地源描述了用户日历中的“在我的 iphone 上”、“icloud”、“gmail”等字段。在我的代码中,当用户设置了 icloud 帐户但没有授予 icloud 帐户写入日历的权限时,本地源为空。因此,即使应用程序具有写入日历的权限,但本地源为零,因此,将事件添加到日历也会失败。

我的代码在给定的 2 种情况下添加到日历:

  1. 用户已登录 icloud 并已授予 icloud 写入日历的权限。在这种情况下,本地源不为零,并且在“iCloud”中使用名称“someName”创建日历。
  2. 用户尚未登录 icloud。现在,在“在我的 iphone 上”本地源中创建了名称为“someName”的日历。