微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何识别EKCalendar以存储用户日历选择

如何解决如何识别EKCalendar以存储用户日历选择

使用用户日历时,我实现了EKCalendarChooser,它允许用户选择多个日历。所选日历实例的检索就很好。现在,我以后要使用此选择,但是如何将其永久存储?

enter image description here

我的第一种方法是使用日历标识符并将其作为字符串数组存储到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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。