Swift 3创建提醒EKEventStore

时间:2017-03-15 21:50:54

标签: swift3 eventkit reminders

我想将提醒保存到默认提醒位置。但是当我按下我的按钮时,我得到一个致命的错误:在打开一个Optional值时意外地发现了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)")
    }

   } 
 }

2 个答案:

答案 0 :(得分:3)

作为一段简单的代码,我想我会在找到任何未来的快捷方式之后发布我的答案。我总是喜欢简单的例子。

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.
}


}

答案 1 :(得分:0)

对于@adamprocter示例,我们还需要在info.plist文件中的消息中添加“ NSRemindersUsageDescription”键。我尝试将其添加为评论,但我不符合条件。