import EventKit
lazy var eventStore = EKEventStore()
/// 系統(tǒng)日歷添加提醒事件
/// - Parameter eventTitle: event 名字
/// - Parameter eventNotes: event 信息
/// - Parameter eventRepeatTime: event 重復(fù)提醒時(shí)間 Date 類型 精確到分鐘
/// - Parameter eventEndTime: event 結(jié)束時(shí)間 Date 類型
/// - Parameter eventRepeatDate: event 重復(fù)日 例: 0, 1, 2 0 為周日 以此類推
/// - Parameter eventAlarmTime: event 提醒時(shí)間 單位: min 為空 則不提醒
/// - Parameter eventIdentifier: event Block 系統(tǒng)分配事件 identifier
/// - Parameter eventAddFailure: event Block 添加失敗 一般會(huì)是 權(quán)限問(wèn)題
func addACalendarTime(_ eventTitle: String,
eventNotes: String,
eventRepeatTime: Date,
eventEndTime: Date,
eventRepeatDate: String?,
eventAlarmTime: Int?,
eventIdentifier: @escaping ((_ identifier: String) -> Void),
eventAddFailure: @escaping (() -> Void)) {
let event = EKEvent(eventStore: self.eventStore)
event.title = eventTitle
event.notes = eventNotes
event.startDate = eventRepeatTime
event.endDate = eventRepeatTime
event.isAllDay = false
if let time = eventAlarmTime {
event.addAlarm(EKAlarm(relativeOffset: TimeInterval(-60 * time)))
}
event.calendar = self.eventStore.defaultCalendarForNewEvents
var weekArr: [EKRecurrenceDayOfWeek] = []
if let wt = eventRepeatDate {
let wArr = wt.components(separatedBy: ",")
for index in 0..<wArr.count {
let weekInt: Int = Int(wArr[index]) ?? -1
if weekInt > -1 {
let daysOfWeek = EKRecurrenceDayOfWeek(EKWeekday.init(rawValue: weekInt + 1)!)
weekArr.append(daysOfWeek)
}
}
}
let rule = EKRecurrenceRule(recurrenceWith: .weekly,
interval: 1,
daysOfTheWeek: weekArr,
daysOfTheMonth: nil,
monthsOfTheYear: nil,
weeksOfTheYear: nil,
daysOfTheYear: nil,
setPositions: nil,
end: EKRecurrenceEnd(end: eventEndTime))
event.addRecurrenceRule(rule)
do {
try self.eventStore.save(event, span: .thisEvent)
eventIdentifier(event.eventIdentifier)
PLLog("添加成功")
}catch {
PLLog("添加失敗")
}
}