我正在使用以下优秀代码:
func addEventToCalendar(title: String, description: String?, startDate: NSDate, endDate: NSDate, completion: ((success: Bool, error: NSError?) -> Void)? = nil) {
let eventStore = EKEventStore()
eventStore.requestAccessToEntityType(.Event, completion: { (granted, error) in
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.allDay = true
event.startDate = startDate
event.endDate = endDate
event.notes = description
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.saveEvent(event, span: .ThisEvent)
} catch let e as NSError {
completion?(success: false, error: e)
return
}
completion?(success: true, error: nil)
} else {
completion?(success: false, error: error)
}
})
}
但我如何检查事件是否已经存在?
答案 0 :(得分:8)
例如,您可以使用与活动相同的设置检查日历上的活动。您可以使用NSPredicate
:
let startDate = yourStartDate
let endDate = yourEndDate
let predicate = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: nil)
let existingEvents = eventStore.eventsMatchingPredicate(predicate)
for singleEvent in existingEvents {
if singleEvent.title == yourEventTitle && singleEvent.startDate == yourStartDate {
// Event exist
...
}
}