我在使用Swift时尝试在iOS的日历应用程序上创建新事件时遇到了问题。
这是我到目前为止所做的:
func addToCal(){
let eventStore = EKEventStore()
eventStore.requestAccessToEntityType(EKEntityTypeReminder) {
(granted: Bool, err: NSError!) in
if granted && !err {
var event:EKEvent = EKEvent(eventStore: eventStore)
event.title = self.eventTitle!.text
event.startDate = self.eventData.startDateObj
event.endDate = self.eventData.endDateObj
event.calendar = eventStore.defaultCalendarForNewEvents
eventStore.saveEvent(event, span: EKSpanThisEvent, error: nil)
println("Saved Event")
}
}
这是我得到的错误:
Error getting default calendar for new events: Error Domain=EKCADErrorDomain Code=1013 "The operation couldn’t be completed. (EKCADErrorDomain error 1013.)"
我检查了我的语法,我很确定我做对了,所以有人能帮我弄明白我哪里出错吗?
将EKEntityTypeReminder
更改为EKEntityTypeEvent
(抱歉,我的错误)实际上不会产生错误,但现在该事件甚至没有显示在日历中。我检查了granted
和err
的输出,我分别看到false
和nil
。
答案 0 :(得分:0)
我认为你的主要问题是你没有提交要保存的新事件。以下代码是我使用的,主要区别在于我的代码包含一个提交,并允许我的错误从'nil'更改(如果有的话)。最后的条件只会打印任何保存错误报告或将成功保存到调试区域。
let eventStore = EKEventStore()
let event = EKEvent(eventStore: eventStore)
event.title = "Your Event Title Here" // Sets event's title
event.startDate = NSDate() // Sets event's start date
event.endDate = event.startDate.dateByAddingTimeInterval(20000) // Sets event's end date
event.calendar = eventStore.defaultCalendarForNewEvents // Selects default calendar
var saveError : NSError? = nil // Initially sets errors to nil
eventStore.saveEvent(event, span: EKSpanThisEvent, commit: true, error: &saveError) // Commits changes and allows saveEvent to change error from nil
//// Following checks for errors and prints result to Debug Area ////
if saveError != nil {
println("Saving event to Calendar failed with error: \(saveError!)")
} else {
println("Successfully saved '\(event.title)' to '\(event.calendar.title)' calendar.")
}
希望这有帮助!
-Gorowski