用的第三方库:Timepiece
//判断是否有该事件(现在-180天内这段时间)
func setHaveCalendar(docid:String , successed:@escaping (_ responseObject: NSArray?) -> ()) {
eventStore.requestAccess(to: .event, completion: {
granted, error in
if (granted) && (error == nil) {
let calendars = self.eventStore.calendars(for: .event).filter({ (calender) -> Bool in
return calender.type == .local || calender.type == .calDAV
})
let startDate = Date().addingTimeInterval(0)
let endDate = Date().addingTimeInterval(3600*24*180)
let predicate2 = self.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: calendars)
let events: [EKEvent] = self.eventStore.events(matching: predicate2)
let eventss = events.filter({ (eventt) -> Bool in
if eventt.notes == docid{
print("eventt.notes = \(String(describing: eventt.notes)) docid = \(docid)" )
return true
}
return false
})
successed(eventss as NSArray)
}
})
}
//写进日历提醒事项进去
func WriteToEvents(model:MainDataModel, successed:@escaping (_ responseObject: Bool?) -> ()){
if model.alerttime != nil && model.alerttime != ""{
eventStore.requestAccess(to: .event, completion: {
granted, error in
if (granted) && (error == nil) {
let event:EKEvent = EKEvent(eventStore: self.eventStore)
event.title = model.maincontent
event.location = model.geopos;
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd HH:mm"
event.endDate = dateformatter.date(from: model.alerttime)!
event.startDate = (event.endDate - 30.minutes)!
event.notes = model.docid
event.calendar = self.eventStore.defaultCalendarForNewEvents
event.addAlarm(EKAlarm.init(absoluteDate: event.startDate))
do{
try self.eventStore.save(event, span: .thisEvent)
successed(true)
}catch{
print(error)
successed(false)
}
}
})
}
}
//取消日历提醒
func CancelEvents(docid:String ,successed:@escaping (_ responseObject: Bool?) -> ()){
self.setHaveCalendar(docid: docid) { (array) in
for i in array!{
do {
try self.eventStore.remove(i as! EKEvent, span: .thisEvent)
successed(true)
} catch {
print(error)
successed(false)
}
}
}
}