iosswiftekcalendar

How can I set my default calendar when done is pressed?


I want the user to be able to chose a new default calendar with the EKCalendarChooser. So far this is what I thought that might work but it is not.

   func calendarChooserDidFinish(_ calendarChooser: EKCalendarChooser) {
    print("Done was pressed")
    // Set to default calendar
    eventStore.defaultCalendarForNewReminders()
    for source in eventStore.sources {
        if source.sourceType == .local {
            calendar.source = source
            break
        }
    }
    dismiss(animated: true, completion: nil)
}

How can I set a new default calendar with the EKCalendarChooser?


Solution

  •  //get your calendar if it was previously created
        let calendars = eventStore.calendars(for: .event)
        for c in calendars
        {
            if c.title == "calendarName"
            {
                calendar = c
            }
        }
    
    //create it if it was not created previously
        if calendar == nil
        {
            let calendar = EKCalendar(for: .event, eventStore: eventStore)
            calendar.title = "calendarName"
            if eventStore.sources.count == 0
            {
                calendar.source = EKSource()
            }
            else
            {
                self.setStoreForCalendar(calendar: calendar, store: eventStore)
            }
            do
            {
                try eventStore.saveCalendar(calendar, commit: true)
            }
            catch let err as NSError
            {
                print ("error  \(err.description)")
            }
        }
    
    //set defaultCalendar 
        func setStoreForCalendar(calendar:EKCalendar, store:EKEventStore)
        {
            var mSource:EKSource?
            for source in store.sources
            {
                if source.sourceType == .calDAV && source.title == "iCloud"
                {
                    mSource = source
                }
            }
    
            if mSource == nil
            {
                // saving on the local calendar
                mSource = store.defaultCalendarForNewEvents?.source
            }
        }