0

I would like to save reminders to the default reminders location. But when I press my button I get a fatal error: unexpectedly found nil while unwrapping an Optional value... I am pretty new to this and most examples I locate are overly complicated or not in Swift 3.

class ViewController: UIViewController {

var eventStore: EKEventStore?

@IBOutlet weak var reminderText: UITextField!

@IBAction func setReminder(_ sender: Any) {

    let reminder = EKReminder(eventStore: self.eventStore!)

    reminder.title = "Go to the store and buy milk"
    reminder.calendar = (eventStore?.defaultCalendarForNewReminders())!

    do {
        try eventStore?.save(reminder,
                             commit: true)
    } catch let error {
        print("Reminder failed with error \(error.localizedDescription)")
    }

   } 
 }
adamprocter
  • 856
  • 1
  • 15
  • 31

2 Answers2

5

As its a simple piece of code I thought I would post my answer after I figured it out for any future swifters. I always like simple examples.

import UIKit
import EventKit

class ViewController: UIViewController {

var eventStore = EKEventStore()
var calendars:Array<EKCalendar> = []

// Not used at this time
@IBOutlet weak var reminderText: UITextField!

@IBAction func setReminder(_ sender: Any) {


    let reminder = EKReminder(eventStore: self.eventStore)

    reminder.title = "Go to the store and buy milk"
    reminder.calendar = eventStore.defaultCalendarForNewReminders()

    do {
        try eventStore.save(reminder,
                            commit: true)
    } catch let error {
        print("Reminder failed with error \(error.localizedDescription)")
    }

}



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

  // get permission
    eventStore.requestAccess(to: EKEntityType.reminder, completion:
        {(granted, error) in
            if !granted {
                print("Access to store not granted")
            }
    })

 // you need calender's permission for the reminders as they live there
    calendars = eventStore.calendars(for: EKEntityType.reminder)

    for calendar in calendars as [EKCalendar] {
        print("Calendar = \(calendar.title)")
    }

}


override func viewWillAppear(_ animated: Bool) {
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}
adamprocter
  • 856
  • 1
  • 15
  • 31
0

With the @adamprocter sample, we also need to add "NSRemindersUsageDescription" key with your message in info.plist file. I tried adding this as a comment but I am not eligible.

Ganesh
  • 58
  • 8