问题描述
使用用户日历时,我实现了EKCalendarChooser,它允许用户选择多个日历。所选日历实例的检索就很好。现在,我以后要使用此选择,但是如何将其永久存储?
我的第一种方法是使用日历标识符并将其作为字符串数组存储到UserDefaults之类的
@State private var calendarSelection: [EKCalendar]
// my approach to convert the calendar selection into a storable format (string array of ids)
var selectedIds = [String]()
for calendar in calendarSelection {
selectedIds.append(calendar.calendarIdentifier)
}
// Now store the string-array,eg. to user defaults:
UserDefaults.standard.set(selectedIds,forKey: "cids")
不幸的是,这是行不通的,因为calendarIdentifier
不是永久性标识符,因此会随着时间而改变。正如苹果在其文档中所述:
然后如何存储用户对日历的选择?
解决方法
好,现在对我有用。
我存储日历标识符...
func calendarChooserDidFinish(_ calendarChooser: EKCalendarChooser) {
...
// store selected calendar identifier
selectedCalendar = calendarChooser.selectedCalendars.first?.calendarIdentifier
...
}
...然后将其还原。
func showCalendarChooser() {
...
// check if calendar identifier still exists
if let selectedCalendarIdentifier = eventStore.calendar(withIdentifier: selectedCalendar) {
//select stored calendar
calendarChooser.selectedCalendars = [selectedCalendarIdentifier]
}
...
}
这仅适用于1个选定的日历(selectionStyle: .single
)。
将此代码更改为多个日历应该很简单。
我还测试了日历标识符是否可能会更改...到目前为止还算不错。在所有测试中均保持不变。如果应该更改(nil
,则不会选择任何日历,并且该应用不会崩溃。
HTH