在EKEventStore中创建EKCalendar - Swift

时间:2015-03-26 18:38:31

标签: swift ios8 eventkit ekeventstore

当我的应用程序首次运行时,我正在尝试在EKEventStore中创建一个日历。我发现this tutorial但是我对Objective-C并不是很了解将其翻译成Swift,而且从我已经完成的研究中我也很想知道这种方法是否仍然适用于ios8。

1 个答案:

答案 0 :(得分:2)

尝试(注意这是一个提醒类型,但您可以根据需要更改类型):

let eventStore = EKEventStore()
var yourReminderCalendar: EKCalendar?

func retrieveYourCalendar() {
    let calendars = eventStore.calendarsForEntityType(EKEntityTypeReminder)

    if(yourReminderCalendar == nil) {
        for calendar in calendars {
            if calendar.title == "Your Title" {
                yourReminderCalendar = (calendar as EKCalendar)
                break
            }
        }

        if(yourReminderCalendar == nil) {
            yourReminderCalendar = EKCalendar(forEntityType: EKEntityTypeReminder, eventStore: eventStore)
            yourReminderCalendar!.title = "Your Title"
            yourReminderCalendar!.source = eventStore.defaultCalendarForNewReminders().source
            var error: NSError?

            if(eventStore.saveCalendar(yourReminderCalendar, commit: true, error: &error)) {
                println("reminder cal saved")
            }
            else {
                //HANDLE REMINDER ERROR
            }
        }
    }
}

您想要检查授权:

    func verifyUserEventAuthorization() {
    switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeReminder) {
    case .Authorized:
        ...
    case .Denied:
        ...
    case .NotDetermined:
        eventStore.requestAccessToEntityType(EKEntityTypeReminder, completion:
            { [weak self](granted: Bool, error: NSError!) -> Void in
                if granted {
                    ...
                }
                else {
                   ...
                }
        })
    case .Restricted:
        ...
    }
}