Swift 4.0 Eventkit Cannot get calendars and events correctly

≯℡__Kan透↙ 提交于 2019-12-20 16:25:12

问题


I'm trying to use Eventkit to access Mac Calendar. Access is successfully requested but I keep getting nil or an empty array of calendar or events, even though I have several calendars and many eventsin local calendar, iCloud calendar, and Google calendar in the app.
The output I get from the following code is: On My Mac [] []

    let sources = eventStore.sources
    for source in sources{
        print(source.title)
        for calendar in source.calendars(for: .event){
            print(calendar.title)
        }
    }

    let calendars = eventStore.calendars(for: .event)
    let predicate = self.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: nil)
    let events = self.eventStore.events(matching: predicate)
    print(calendars)
    print(events)

And if I try to create and save a calendar from code, then I'm getting error: Error Domain=EKErrorDomain Code=5 "Attempted to save when persistence was unavailable" UserInfo={NSLocalizedDescription=Attempted to save when persistence was unavailable}


回答1:


After lots of trial and error, I found the answer.

You need to set the com.apple.security.personal-information.calendars key to YES in your entitlements file, even if your app is not sandboxed. There is a bug in Apple's implementation of EventKit that prevents your app getting access to calendars if it does not set this key, even if the sandbox is disabled.




回答2:


I might be wrong but you are missing one parameter in your predicate you are passing in nil so there is nothing to sort essentially no output. Try changing your code to:

 let sources = eventStore.sources
    for source in sources{
        print(source.title)
        for calendar in source.calendars(for: .event){
            print(calendar.title)
        }
    }

    let calendars = eventStore.calendars(for: .event)
    let predicate = self.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: calendars)  //change here
    let events = self.eventStore.events(matching: predicate)
    print(calendars)
    print(events)


来源:https://stackoverflow.com/questions/49525592/swift-4-0-eventkit-cannot-get-calendars-and-events-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!