Retrieving iOS calendar event with EventKit

To retrieve iOS calendar event, we need to work with EventKit. First we will create a EKEventStore, then we need to request permission to use EventKit.

import Foundation
import EventKit

class EventKitDataModel {
    private let eventStore = EKEventStore()
   
    func authorizeEventKit(completion: @escaping EKEventStoreRequestAccessCompletionHandler) {
        eventStore.requestAccess(to: EKEntityType.event) { (accessGranted, error) in
            completion(accessGranted, error)
        }
    }
}

Once we have the permission, getting calendar events from the event score is quite straightforward. In this example we are going to query the event store to get a list of calendar events happening during a set of Date. Adding the two functions below to the class:

func collectData(since: Date, until: Date) {  
        let timefilter = self.makeTimePredicate(since: since, until: until)
        
        //Load events
        var events: [EKEvent]? = nil
        events = eventStore.events(matching: timefilter)
        if let allevents = events {
            for event in allevents {
                //Do something to the event
                //e.g. Get the title of the event
                let eventtitle = event.title!
            }
        }
    }

func makeTimePredicate (since startDate: Date, until endDate: Date) -> NSPredicate {
        return eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: nil)
    }

Here we create a function, which takes a “since date” and an “until date”. We create a time predicate using the two dates, and then query the event store using eventStore.events(matching: <predicate>) to get an array of all events within the two dates. The predicate is created by predicateForEvents(). The events are represented as EKEvent. Please consult the Swift manual for more information.

Leave a ReplyCancel reply