Search code examples
swifteventkit

eventStore.saveCalendar returns an error "json error: An unexpected error occurred."


I am trying to implement the same code in https://www.andrewcbancroft.com/2015/06/17/creating-calendars-with-event-kit-and-swift/, but I get an error stating "json error: An unexpected error occurred." I am developing this project for macOS.

This is my following code,

@IBAction func addPressed(_ sender: NSButton) {

    // Create an Event Store instance
    let eventStore = EKEventStore();

    // Use Event Store to create a new calendar instance
    // Configure its title
    let newCalendar = EKCalendar(for: .event, eventStore: eventStore)

    // Probably want to prevent someone from saving a calendar
    // if they don't type in a name...
    newCalendar.title = "DCU"

    // Access list of available sources from the Event Store
    let sourcesInEventStore = eventStore.sources

    // Filter the available sources and select the "Local" source to assign to the new calendar's
    // source property
    newCalendar.source = sourcesInEventStore.filter{
        (source: EKSource) -> Bool in
        source.sourceType.rawValue == EKSourceType.local.rawValue
        }.first!

    // Save the calendar using the Event Store instance
    do {
        try eventStore.saveCalendar(newCalendar, commit: true)
    } catch {
        print("json error: \(error.localizedDescription)")
    }
}

When I build the project and click run it gives me the error "json error: An unexpected error occurred.". When I try to add an event to defaultcalendar it gives me an error "json error: No calendar was set". I have tried all the available sources online but couldn't find a solution. Somehow neither eventStore.save or eventStore.saveCalendar is working for me. Can someone please let me know where might I be going wrong?


Solution

  • Two possible reasons

    1. From the documentation of EKEventStore

      To access the user’s Calendar data, all sandboxed macOS apps must include the com.apple.security.personal-information.calendars entitlement. To learn more about entitlements related to App Sandbox, see Enabling App Sandbox.

    2. Check the authorizationStatus of the store and call requestAccess if necessary.


    Your error message is misleading, the error has nothing to do with JSON.