How to use EKEventEditViewController in SwiftUI

My finished solution to bridging this view controller for creating new events and editing existing ones to SwiftUI.

Published: Aug. 4, 2020
See books

I have made another notable progress porting my EKEventKit Example app to SwiftUI with bridging the EKEventEditViewController. This ready-made controller will let you create new event and save it as well and also edit existing events that you can pass in.

This time I could draw inspiration from using EKCalendarChooser in SwiftUI from my previous post.

Complete code

Below is fully working code to use EKEventEditViewController in your SwiftUI.

import SwiftUI
import EventKitUI

struct EventEditView: UIViewControllerRepresentable {
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

    @Environment(\.presentationMode) var presentationMode

    let eventStore: EKEventStore
    let event: EKEvent?

    func makeUIViewController(context: UIViewControllerRepresentableContext<EventEditView>) -> EKEventEditViewController {

        let eventEditViewController = EKEventEditViewController()
        eventEditViewController.eventStore = eventStore

        if let event = event {
            eventEditViewController.event = event // when set to nil the controller would not display anything
        }
        eventEditViewController.editViewDelegate = context.coordinator

        return eventEditViewController
    }

    func updateUIViewController(_ uiViewController: EKEventEditViewController, context: UIViewControllerRepresentableContext<EventEditView>) {

    }

    class Coordinator: NSObject, EKEventEditViewDelegate {
        let parent: EventEditView

        init(_ parent: EventEditView) {
            self.parent = parent
        }

        func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
            parent.presentationMode.wrappedValue.dismiss()

            if action != .canceled {
                NotificationCenter.default.post(name: .eventsDidChange, object: nil) // custom notification to reload UI when events changed
            }
        }
    }
}

Example usage

This can then be used with sheet modifier:

EventEditView(eventStore: self.eventsRepository.eventStore, event: self.selectedEvent)

You can pass nil as event to create new one using the EKEventEditViewController.

Other EventKit posts are available here.

Uses: Xcode 12 & Swift 5.3

Filip Němeček profile photo

WRITTEN BY

Filip Němeček @nemecek_f@iosdev.space

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀