美文网首页
【Swift4.0】 动态添加手机提醒事项

【Swift4.0】 动态添加手机提醒事项

作者: 晴天mk1992 | 来源:发表于2018-01-10 02:00 被阅读0次

    1、首先要在info.plist里面授权app可以使用日历
    Privacy - Reminders Usage Description

    2、导入需要的事件库:EventKit.framework

        var eventStore: EKEventStore!
        @IBAction func onAddAlarmClick(_ sender: Any) {
            self.eventStore = EKEventStore()
            let formatter = DateFormatter.init()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let date = formatter.date(from: "2018-01-10 01:57:00")
            self.eventStore.requestAccess(to: .reminder, completion: { _,error in
                let reminder = EKReminder.init(eventStore: self.eventStore)
                reminder.title = "今天要运动"
                let dueDate = self. dateComponentFromDate(date!)
                reminder.dueDateComponents = dueDate
                reminder.calendar = self.eventStore.defaultCalendarForNewReminders();
    //            添加闹钟
                let alarm = EKAlarm.init(relativeOffset: -5)
                reminder.addAlarm(alarm);
                do {
    //                try self.eventStore.save(event, span: span)
                    try self.eventStore.save(reminder, commit: true)
                    print("保存成!")
                }catch{
                    print("创建失败: \(error)")
                }
            })
            
        }
        //根据NSDate获取对应的NSDateComponents对象
        func dateComponentFromDate(_ date: Date)-> DateComponents{
            let calendarUnit: Set<Calendar.Component> = [.minute, .hour, .day, .month, .year]
            let dateComponents = NSCalendar.current.dateComponents(calendarUnit, from: date)
            return dateComponents
        }
    

    相关文章

      网友评论

          本文标题:【Swift4.0】 动态添加手机提醒事项

          本文链接:https://www.haomeiwen.com/subject/hhennxtx.html