swift 往系统日历中添加提醒事项

前端之家收集整理的这篇文章主要介绍了swift 往系统日历中添加提醒事项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

准备工作

添加EventKit.framework

在当前类import EventKit


实现添加

func addToCalendarClicked()
    {
        let eventStore = EKEventStore()
        eventStore.requestAccessToEntityType(.Event) {(granted,error) in
            
            do {
                if((error) != nil)
                {
                    //添加错误
                }
                else if(!granted)
                {
                    //无访问日历权限
                }
                else
                {
                    let event = EKEvent(eventStore: eventStore)
                    event.title = self.titleName
                    event.location = self.address
                    //起止时间
                    let formatter = NSDateFormatter()
                    formatter.dateFormat = "yyyy-MM-dd HH:mm"
                    let startTime = formatter.dateFromString(self.startDate)
                    let endTime = formatter.dateFromString(self.endDate)
                    print("startTime:\(startTime)")
//                    event.allDay = true
                    event.startDate = startTime!
                    event.endDate = endTime!
                    //在事件前多少秒开始事件提醒
                    let alarm = EKAlarm()
                    alarm.relativeOffset = -60.0
                    event.addAlarm(alarm)
                    event.calendar = eventStore.defaultCalendarForNewEvents
                    let result:()? = try eventStore.saveEvent(event,span: EKSpan.ThisEvent)
                    print("result:\(result)")
                    if(result != nil)
                    {
                        self.creatMyAlert("提示",message: "已成功添加到日历",isRegister: false)
                    }
                }
            }
            catch {
                print("error")
            }
        }
       
    }

说明:其中的

do{

}

catch{

}

是为了解决itisnotmarked with'try'and the errornothandled..错误,参考:这里

原文链接:https://www.f2er.com/swift/323753.html

猜你在找的Swift相关文章