`enum CalendarType: String {
case appointment = "Vyhnes Appointment"
case event = "Vyhnes Event"
case shipment = "Vyhnes Shipment"
static var all = [appointment.rawValue, event.rawValue,
shipment.rawValue]
}`
func createCalendarGroups(completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
let eventStore = EKEventStore()
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
CalendarType.all.forEach({ (calendarName) in
if UserDefaults.standard.value(forKey: calendarName) == nil {
let newCalendar = EKCalendar(for: .event, eventStore: eventStore)
newCalendar.title = calendarName
let sourcesInEventStore = eventStore.sources
newCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
do {
try eventStore.saveCalendar(newCalendar, commit: true)
UserDefaults.standard.set(newCalendar.calendarIdentifier, forKey: calendarName)
} catch {
let alert = UIAlertController(title: "Calendar could not save", message: (error as NSError).localizedDescription, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
}
})
completion?(true, nil)
} else {
completion?(false, error as NSError?)
print(error ?? NSError())
}
})
}
//枚举用于三个日历以保存三个不同的字符串名称并在创建日历中。用于遍历枚举 CalendarType 中的 3 个日历名称的函数 forEach 循环以保存在具有三个不同组的本地日历中