更新EKCalendar(提醒列表)时遇多种错误,如何正确更新?
解决提醒列表更新失败的问题
问题根源
直接使用之前存储的existingCalendar对象进行更新时,该对象可能已与EKEventStore的上下文脱节,或是其关联的账户状态发生了变化,这会触发That account does not support reminders.错误;而强行修改source属性则违反了「提醒列表创建后无法跨账户移动」的系统限制,导致That calendar may not be moved to another account.错误。
正确的更新步骤
从
EKEventStore重新获取最新日历实例
不要直接复用存储的对象,而是通过日历的calendarIdentifier从事件商店拉取当前有效的实例,确保操作的是与上下文绑定的最新对象。仅修改允许更新的属性
不要改动source属性——提醒列表的账户归属一旦确定就无法变更,只需更新标题、颜色这类可修改的属性。调用保存方法提交更改
复用原有的saveCalendar(_:commit:)方法提交更新,保持commit: true确保更改同步到系统日历。
完整代码示例
let ekStore = EKEventStore() // 通过ID获取最新的日历实例 func fetchCalendar(withIdentifier id: String) -> EKCalendar? { return ekStore.calendar(withIdentifier: id) } // 复用原有的保存方法 func saveCalendar(calendar: EKCalendar) throws { try ekStore.saveCalendar(calendar, commit: true) } // 更新提醒列表的核心逻辑 func updateReminderList(existingCalendarId: String, newTitle: String, newColor: CGColor) { guard let updatedList = fetchCalendar(withIdentifier: existingCalendarId), updatedList.entityType == .reminder else { print("无效的提醒列表ID") return } // 仅修改允许更新的属性 updatedList.title = newTitle updatedList.cgColor = newColor do { try saveCalendar(calendar: updatedList) print("提醒列表更新成功") } catch { print("更新失败: \(error.localizedDescription)") } }
调用示例
只需传入你存储的日历ID、新标题和颜色即可:
// existingCalendarId为你之前存储的日历唯一标识 updateReminderList(existingCalendarId: existingCalendarId, newTitle: "新列表名称", newColor: UIColor.green.cgColor)
内容的提问来源于stack exchange,提问作者Marin
相关产品推荐
相关产品推荐

