How to prevent EventStore access error on first run

Viewed 401

My Mac application accessing the user calendar shows a permission access error on the first run before asking the user for Calendar access permission. The message does not appear on later runs. How can I prevent it? I use the following code:

class MyCalendar {
   let store = EKEventStore()
   init() {
      func requestAccessToCalendar() {           
          store.requestAccess(to: .event, completion:
            {(granted: Bool, error: Error?) -> Void in
          })
      }
      func loadCalendars() {
          calendars = store.calendars(for: .event)
      }

      let ekstatus = EKEventStore.authorizationStatus(for: EKEntityType.event)
      switch (ekstatus) {
         case EKAuthorizationStatus.notDetermined:
            requestAccessToCalendar()
         case EKAuthorizationStatus.authorized:      
            loadCalendars()         
         case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:            
            dialogOK("access to Calendar denied")
         @unknown default:
            dialogOK("Unknown Calendar access problem")
         }
   }
}

The error occurs before any statement in the init() is executed. I also tried with a lazy var instead of a constant for store - without success. The plist entitlement is properly set an the application works as expected beside this error messages.

What is my mistake?

1 Answers

I struggled with this for a while as well. As hinted elsewhere, you likely need to add the reason to the Info.plist, e.g.:

<dict>
    <key>NSCalendarsUsageDescription</key>
    <string>Export event information</string>
</dict>
Related