Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a reminder in iOS Swift

I am trying to set a simple EKReminder in my swift application to remind users to catch the bus. However, when I try to save my reminder, I always get a error (no error is reported, the app just crashes). I have the code below.

public class func createReminder(reminderTitle: String, timeInterval:      NSDate) {
    var calendarDatabase = EKEventStore()

    calendarDatabase.requestAccessToEntityType(EKEntityTypeReminder,
        completion: nil)

    let reminder = EKReminder(eventStore: calendarDatabase)

    reminder.title = reminderTitle

    let alarm = EKAlarm(absoluteDate: timeInterval)

    reminder.addAlarm(alarm)

    reminder.calendar = calendarDatabase.defaultCalendarForNewReminders()

    var error: NSError?

    calendarDatabase.saveReminder(reminder, commit: true, error: &error)
}
like image 440
applejuiceteaching Avatar asked Sep 28 '22 10:09

applejuiceteaching


1 Answers

The following should work in Swift 4.2

func AddReminder() {

 eventStore.requestAccess(to: EKEntityType.reminder, completion: {
  granted, error in
  if (granted) && (error == nil) {
    print("granted \(granted)")


    let reminder:EKReminder = EKReminder(eventStore: self.eventStore)
    reminder.title = "Must do this!"
    reminder.priority = 2

    //  How to show completed
    //reminder.completionDate = Date()

    reminder.notes = "...this is a note"


    let alarmTime = Date().addingTimeInterval(1*60*24*3)
    let alarm = EKAlarm(absoluteDate: alarmTime)
    reminder.addAlarm(alarm)

    reminder.calendar = self.eventStore.defaultCalendarForNewReminders()


    do {
      try self.eventStore.save(reminder, commit: true)
    } catch {
      print("Cannot save")
      return
    }
    print("Reminder saved")
  }
 })

}

info.plist requires appropriate privacy settings as well. enter image description here

like image 198
Mike Chirico Avatar answered Nov 06 '22 09:11

Mike Chirico