I want to write a method, that takes a event object, which has a name and a date parameters. The function requests access / checks access to the event store, creates an EKEvent with the parameters, saves it to the store and then returns the eventidentifier as a String.
So far I have trouble because the eventStore.requestAccess(To:) methods closure escapes, and the string is returned before the EKEvent object actually is created and saved to the store.
My method sits in the code of my EventHelper class, that is the abstraction layer between my EventStore and Apples EKEventStore.
import EventKit
struct Event {
var name: String
var date: Date
var id: String?
}
class EventHelper {
// MARK: Properties
var store: EKEventStore!
// MARK: Methods
func createCalendarEvent(for event: Event) -> String? {
// Prepare a place to store the eventIdentifier
var identifier : String?
// Get access to the eventstore
store.requestAccess(to: .event) { (granted, error) in
if (granted) && (error == nil) {
print("Calendar event creation.")
print("granted: \(granted)")
print("error: \(String(describing: error))")
// Create a new event kit event
let newEvent = EKEvent(eventStore: self.store)
newEvent.title = event.name
newEvent.startDate = event.date
// Create a timeinterval for the end date
let twoHourTimeInterval = TimeInterval(exactly: 7200)
newEvent.endDate = event.date.addingTimeInterval(twoHourTimeInterval!)
// choose the calendar the event should be assigned to
newEvent.calendar = self.store.defaultCalendarForNewEvents
// try to save the new event in the event store
do {
try self.store.save(newEvent, span: .thisEvent, commit: true)
identifier = newEvent.eventIdentifier
print("Saved event with ID: \(String(describing: newEvent.eventIdentifier))")
// The event gets created and the ID is printed to the console but at a time when the whole function already has returned (nil)
} catch let error as NSError {
print("Failed to save event with error: \(error)")
}
}
else {
print("Failed to save event with error \(String(describing: error)) or access not granted")
}
}
print("new Event: \(String(describing: identifier))")
return identifier
}
}