Swift3将事件添加到日历提醒事项

iOS10之后如果需要调用系统日历,需要在info.plist文件中添加键Privacy - Calendars Usage Description并作出相应描述,使用日历需要引入EventKit框架。

封装方法

import UIKit
import EventKit

class EventCalender: NSObject {
    
    public static let sharedEventCalender = EventCalender()
    private override init() {}

    /**
     *  将事件添加到系统日历提醒事项
     *
     *  @param title      事件标题
     *  @param location   事件位置
     *  @param startDate  开始时间
     *  @param endDate    结束时间
     *  @param allDay     是否全天
     *  @param before     在事件前多少秒开始提醒
     */
    public func creatEventCalender(title:String,
                                   location:String,
                                   startDate:Date,
                                   endDate:Date,
                                   allDay:Bool,
                                   before:Double){
        let eventStore = EKEventStore()
        eventStore.requestAccess(to: EKEntityType.event, completion: { (granted, error) in
            do{
                guard granted else{
                    print("没有日历访问权限")
                    return
                }
                guard error == nil else{
                    //错误处理
                    print(error ?? "怎么可能没有错误")
                    return
                }
                let event = EKEvent(eventStore: eventStore)
                event.title = title
                event.location = location
                event.startDate = startDate
                event.endDate = endDate
                event.isAllDay = allDay
                //在事件前多少秒开始时间提醒
                let alarm = EKAlarm(relativeOffset: -before)
                event.addAlarm(alarm)
                event.calendar = eventStore.defaultCalendarForNewEvents
                let result: ()? = try eventStore.save(event, span: EKSpan.thisEvent)
                if result != nil{
                    //添加成功
                    print("添加成功")
                }else{
                    //添加失败
                    print("添加失败")
                }
            }catch{
                print("出现异常")
            }
        })
    }
}

调用方法

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let startTime = formatter.date(from: "2017-7-6 10:45")
let endTime = formatter.date(from: "2017-7-6 10:46")
        
EventCalender.sharedEventCalender.creatEventCalender(title: "提醒测试", location: "", startDate: startTime!, endDate: endTime!, allDay: false, before: 10)

你可能感兴趣的:(Swift3将事件添加到日历提醒事项)