我该如何修复错误 "No start date has been set"?

How I can fix error "No start date has been set"?

在常规日历中保存活动时,有时不会保存活动。显示错误:"failed to save event with error: Error Domain = EKErrorDomain Code = 2" No start date has been set. "UserInfo = {NSLocalizedDescription = No start date has been set.}",虽然日期确定正确

func saveTaskInCalendar() {
        let eventStore : EKEventStore = EKEventStore()
        eventStore.requestAccess(to: .event) { (granted, error) in
            if (granted) && (error == nil) {
                let event: EKEvent = EKEvent(eventStore: eventStore)
                DispatchQueue.main.async {
                    event.title = "Test"
                    event.startDate = Date()
                    event.endDate = Date()
                }
                event.calendar = eventStore.defaultCalendarForNewEvents
                do {
                    try eventStore.save(event, span: .thisEvent)
                } 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")
            }
        }
    }

如何修复此错误?

问题是您将 EKEvent 的属性设置包装在调度异步块中,同时将事件保存在异步块之外。这可能会导致 属性 设置在 之后 您已经尝试保存事件。

要么删除 DispatchQueue.main.async 调用,因为它无论如何都不是必需的,要么将保存代码也放在调度异步中。

let event: EKEvent = EKEvent(eventStore: eventStore)
event.title = "Test"
event.startDate = Date()
event.endDate = Date()
event.calendar = eventStore.defaultCalendarForNewEvents
do {
    try eventStore.save(event, span: .thisEvent)
}

DispatchQueue.main.async {
    let event: EKEvent = EKEvent(eventStore: eventStore)
    event.title = "Test"
    event.startDate = Date()
    event.endDate = Date()
    event.calendar = eventStore.defaultCalendarForNewEvents
    do {
        try eventStore.save(event, span: .thisEvent)
    }
...