Swift 3 创建提醒 EKEventStore

Swift 3 Create Reminder EKEventStore

我想将提醒保存到默认提醒位置。但是当我按下我的按钮时,我得到一个致命错误:在展开可选值时意外发现 nil ...我对此很陌生,我找到的大多数例子都过于复杂或不在 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)")
    }

   } 
 }

由于它是一段简单的代码,我想我会 post 在我为将来的任何 swifter 弄清楚之后我的答案。我总是喜欢简单的例子。

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 示例,我们还需要在 info.plist 文件中添加 "NSRemindersUsageDescription" 密钥和您的消息。我尝试将其添加为评论,但我不符合条件。