SwiftUI中如何接收EKEventStoreChanged通知?
在SwiftUI中接收EKEventStoreChanged通知的正确方式
你之前的问题出在没有指定通知对应的EKEventStore实例——EKEventStoreChanged通知是和具体的eventStore对象绑定的,只有指定了对应的object参数,才能收到该实例发出的数据库变更通知。
正确实现步骤:
- 持有一个全局或可复用的
EKEventStore实例(不要每次需要时临时创建,确保整个生命周期内使用同一个实例) - 创建NotificationCenter publisher时,传入这个
EKEventStore实例作为object参数 - 在SwiftUI View中通过
.onReceive监听该publisher
完整代码示例:
import SwiftUI import EventKit struct CalendarView: View { // 持有EKEventStore实例,建议用@StateObject或全局单例管理 private let eventStore = EKEventStore() // 创建指定了eventStore的publisher private var eventStoreChangedPublisher: NotificationCenter.Publisher { NotificationCenter.default.publisher( for: .EKEventStoreChanged, object: eventStore ) } var body: some View { Text("日历视图") .onReceive(eventStoreChangedPublisher) { _ in print("日历数据库已变更") // 这里执行你的更新逻辑,比如重新加载事件数据 } .onAppear { // 请求日历权限 eventStore.requestAccess(to: .event) { granted, error in if granted { // 权限获取成功后,后续的变更通知才能正常接收 } } } } }
关键说明:
- 必须确保你用来请求权限、操作日历数据的
EKEventStore实例,和你用来监听通知的是同一个实例 - 如果使用临时创建的EKEventStore对象,通知会无法正常触发
- 只有在获取到日历访问权限后,才能接收到变更通知
内容的提问来源于stack exchange,提问作者Marin
相关产品推荐
相关产品推荐

