I am working on a project that creates an event in calendar and saves the eventIdentifier in a Realm DB for later references:
func createCal(eventName: String?, eventDate:Date?) -> String {
var eventId = ""
let eventStore:EKEventStore = EKEventStore()
eventStore.requestAccess(to: .event) { (granted, error) in
if (granted) && (error == nil) {
// print("granted\(granted)")
// print("error\(error)")
let event:EKEvent = EKEvent(eventStore: eventStore)
event.title = eventName
event.startDate = eventDate
event.endDate = event.startDate.addingTimeInterval(3600)
let remider1 = EKAlarm(relativeOffset: -86400)
let remider2 = EKAlarm(relativeOffset: -172800)
event.alarms = [remider1, remider2]
event.notes = "Eveniment autogenerat de aplicatia CARMem"
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent, commit: true)
eventId = event.eventIdentifier
}catch let error as NSError {
print("error\(error)")
}
print("Event Saved")
}else{
print("error\(String(describing: error))")
}
}
return eventId
}
And the function is called in the realm write routine witch is attached to a button:
@IBAction func savePressed(_ sender: UIButton) {
if let currentCategory = selectedCategory.self {EKEventStore.authorizationStatus(for: .event)
do {
try realm.write{
let newEveniment = Eveniment()
newEveniment.title = typeTextField.text! // sa vedem
newEveniment.date = finalDate
let al1Input = Int(al1TextField.text ?? "30")
let al2Input = Int(al2TextField.text ?? "15")
newEveniment.alert1 = al1Input ?? 30
newEveniment.alert2 = al2Input ?? 15
newEveniment.calendarID = createCal(eventName: typeTextField.text, eventDate: finalDate)
print("event salavat in db:\(newEveniment.calendarID)")
currentCategory.sofetEveniment.append(newEveniment)
realm.add(newEveniment)
}
}catch{
print("Eroare la salvarea evenimentului \(error)")
}
}
For the life of me, i dont't understand why the eventId var that is returned is nil. I have tried countless solutions found on stack-overflow but nothing seems to work.
Any help/pointers will be greatly appreciated.
You can get the EKEvent identifier when you actually save the event to calendar.
For example: