Creating an EKCalendar in EKEventStore - Swift

雨燕双飞 提交于 2020-01-01 19:27:10

问题


I'm trying to create a single calendar into EKEventStore when the my app first runs. I found this tutorial but I don't really know enough about Objective-C to translate it to Swift, and also from the research that I've done I'm wondering if this method is still possible in ios8.


回答1:


Try (note this is for a reminder type, but you can just change the type if you need to):

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

You'll want to check for authorization:

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


来源:https://stackoverflow.com/questions/29286359/creating-an-ekcalendar-in-ekeventstore-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!