我如何写入我的 EKEventStore?

How can I write to my EKEventStore?

我之前将我的日历事件保存在 defaultCalendarForNewEvents 中,它正在运行。今天它不再工作但给出错误代码:6 "Calendar is read only".

在我尝试修改日历之前正确请求了权限。为什么它不再起作用,为什么它以前使用相同的代码可以起作用?

注意:我正在使用 XCode 的 iPhone 模拟器进行测试。

代码:

func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) {
    let event = EKEvent(eventStore: eventStore)

    event.title = "Dodgy Codes"
    event.startDate = startDate
    event.endDate = endDate
    event.calendar = eventStore.defaultCalendarForNewEvents

    //Hardcoded testing data
    event.location = "Amsterdam"

    event.notes = "notes notes notes notes"
    do {
        try eventStore.saveEvent(event, span: .ThisEvent)
    } catch let error as NSError {
    //error: Calendar is read only
    print("\(NSStringFromClass(CalendarController)): Adding event: \(error.localizedDescription)")
    }
}

输出

我认为这是授权问题,您需要获得访问日历的权限,这样尝试我希望它对您有用

func checkForEventAuthorization(eventStore: EKEventStore, completionHandler block:(granted: Bool, error: NSError?) -> Void)  {
    if eventStore.respondsToSelector(Selector("requestAccessToEntityType:completion:")) == true {
        eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { (granted, error) -> Void in
            block(granted: granted, error: error)
        })
    } else {
        block (granted: true, error: nil)
    }
}


    func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) {
    self.checkForEventAuthorization(eventStore, completionHandler: { (granted, error) -> Void in
        if granted == true {
            let event = EKEvent(eventStore: eventStore)

            event.title = "Dodgy Codes"
            event.startDate = startDate
            event.endDate = endDate
            event.calendar = eventStore.defaultCalendarForNewEvents

            //Hardcoded testing data
            event.location = "Amsterdam"

            event.notes = "notes notes notes notes"
            do {
                try eventStore.saveEvent(event, span: .ThisEvent)
            } catch let error as NSError {
                //error: Calendar is read only
                print("\(NSStringFromClass(CalendarController)): Adding event: \(error.localizedDescription)")
            }
        }
    })
}

好的,看来这个问题已经解决了,因为它一开始就不存在。我把自己弄糊涂了 运行 在模拟器上,而不是在真实设备上。尝试 运行 iPhone6 上的相同代码有效。在模拟器上它没有! 给初学者的建议:iOS 模拟器并不总是可靠的,在达到一定程度的复杂性后,它变得非常不可靠,尤其是与 EKEventStore 等服务相关的问题。伙计们,最好始终在真实设备上对其进行测试。