Accessing programmatically created calendar on iOS device

前端 未结 2 1860
梦毁少年i
梦毁少年i 2021-01-07 00:54

I have figured out how to add a custom calendar within my iPhone app, but I can\'t figure out how to add that calendar to the device\'s Calendar. The event shows the correct

2条回答
  •  清酒与你
    2021-01-07 01:51

    I've been struggling with this today and it all seems down to what Calendar settings I (and ultimately the end user) has on the device.

    Personally I sync my GMail Calendars down in Exchange format - doing so prevents the "local" calendars from showing up.

    By manipulating the EKSource dependant on the user's settings should display your calendar correctly - this works for my Exchange scenario see the EKSource Class reference for more scenarios. Consider checking for iCloud!

    EKCalendar *calendar = [EKCalendar calendarWithEventStore:self.eventStore];
    calendar.title = @"My Calendar";
    
    EKSource *localSource = nil;
    EKSource *defaultSource = [self.eventStore defaultCalendarForNewEvents].source;
    
    if (defaultSource.sourceType == EKSourceTypeExchange) {
        localSource = defaultSource;
    } else {
    
        for (EKSource *source in self.eventStore.sources) {
            if (source.sourceType == EKSourceTypeLocal) {
                localSource = source;
                break;
            }
        }
    
    }
    
    if (localSource) {
        calendar.source = localSource;
    } else {
        NSLog(@"Error: no local sources available");
    }
    
    NSError *error = nil;
    BOOL result = [self.eventStore saveCalendar:calendar commit:YES error:&error];
    
    if (result) {
    
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:calendar.calendarIdentifier forKey:@"Calendar"];
        [userDefaults synchronize];
    
        NSLog(@"Saved calendar to event store");
    
    } else {
        NSLog(@"Error saving Calendar");
    }
    

提交回复
热议问题