How to Retrieve iOS Calendar Trips with Swift and EventKit 1

How to Retrieve iOS Calendar Trips with Swift and EventKit

This post is going to share an example of how to develop an iOS app to capture calendar events. In order to get calendar events, we need to use EventKit.

To read a calendar, we first need an EKEventStore object, with which we can query the contents of the calendar. Before the app can use the EKEventStore, we need to request permission from the user.

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)
        }
    }
}

As above, we first make an EKEventStore in EventKitDataModel, then authorizeEventKit function will do the action of requesting permission.

With permission, accessing calendar events is easy. The following example retrieves all calendar event itineraries between two dates.

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)
    }

In this function, we use since and until variables to make a TimePredicate called timefilter, which is our query condition. This part is implemented by makeTimePredicate function. Then we can use EKEventStore.events() to get the query result. Each event is an EKEvent object. The example in the later loops simply sets the title of the object to a regional variable.EKEventThe description of the


Thank you for reading this post. If you like my post, please follow up withFacebook Fan Specialist,Twitter,IGThe

Leave a ReplyCancel reply