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

2018-01-10  本文已影响0人  晴天mk1992

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
    }
上一篇下一篇

猜你喜欢

热点阅读