代码语言:javascript复制
import EventKit
/**
Privacy - Calendars Usage Description 添加日历权限 info.list 配置权限
*/
/// 日历添加事件
class KKAddEventClasse: NSObject {
/// 添加成功回调
typealias SuccessAddEvent = ((_ identifier: String) -> Void)
/// 添加失败回调
typealias ErrorAddEvent = ((_ error: String) -> Void)
// 提前一个小时开始
var eventStartDate:Double = 3600
// 提前一分钟结束开始
var eventEndDate:Double = 60
/// 是否添加闹钟 默认添加
var isAddAlarm:Bool = true
/// 添加闹钟(开始前多少秒)若为正则是开始后多少秒。
var addAlarmDate:Double = 60
/// 事件商店
private var eventStore = EKEventStore()
/// 添加事件
/// - Parameter time: "yyyy-MM-dd HH:mm:ss"
open func addEventByTime(time:String,successAddEvent:SuccessAddEvent? = nil,errorAddEvent:ErrorAddEvent? = nil) {
if time.count != "yyyy-MM-dd HH:mm:ss".count {
return
}
eventStore.requestAccess(to: EKEntityType.event, completion: { [weak self](isAllow, error) in
if error != nil {
errorAddEvent?("添加异常")
return
}
if isAllow == true {
self?.addEvent(time:time,successAddEvent:successAddEvent,errorAddEvent:errorAddEvent)
print("允许添加")
} else {
errorAddEvent?("未允许添加")
}
})
}
/// 移除事件 通过事件id
/// - Parameter eventIdentifier: 事件唯一标识
open func removeEnvent(_ eventIdentifier:String){
let event = eventStore.event(withIdentifier: eventIdentifier)
guard event != nil else {
return
}
/// 事件存在
do {
let _ = try eventStore.remove(event!, span: .thisEvent)
} catch {
print(error)
}
}
private func addEvent(time:String,successAddEvent:SuccessAddEvent? = nil,errorAddEvent:ErrorAddEvent? = nil) {
let event = EKEvent.init(eventStore: eventStore)
/// 事件标题
event.title = "事件标题"
event.calendar = eventStore.defaultCalendarForNewEvents
/// 日历显示标题
event.calendar.title = "日历显示标题"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date:Date = formatter.date(from: time) ?? Date()
// 提前一个小时开始
event.startDate = date - eventStartDate
/// 提前一分钟结束
event.endDate = date - eventEndDate
if isAddAlarm {
/// 添加闹钟结合(开始前多少秒)若为正则是开始后多少秒。
event.addAlarm(EKAlarm(relativeOffset: -60))
}
do {
try eventStore.save(event, span: .thisEvent, commit: true)
DispatchQueue.main.async {
successAddEvent?(event.eventIdentifier)
}
} catch {
errorAddEvent?("添加异常")
}
}
}
使用:
代码语言:javascript复制 let event = KKAddEventClasse()
/// 添加
event.addEventByTime(time: "2021-03-01 16:00:00",successAddEvent: { [weak self](eventIdentifier) in
self?.eventIdentifier = eventIdentifier
}, errorAddEvent: {(error) in
print(error)
})
/// 删除
event.removeEnvent(eventIdentifier)