SwiftUI - 访问 EventKitStore 和 store.events(匹配:...)
我正在尝试将 EventKit 与 SwiftUI 结合使用,以便获取用户 iOS 日历上计划事件的简单计数。我已将隐私 - 日历使用说明添加到 Info.plist 文件中并为其添加了值。
这是我的代码。我认为谓词中的 startDate 有问题...但无论我尝试什么,我的 var events:[EKEvent] 总是返回为 0。我应该补充一点,我还在每天我都在努力让它发挥作用。非常感谢您提供的任何帮助!!!!
import EventKit
import Foundation
import SwiftUI
class EventKitManager: ObservableObject {
var store = EKEventStore()
var events: [EKEvent] = []
init() {
requestAccessToCalendar()
todaysEvents()
}
func requestAccessToCalendar() {
store.requestAccess(to: .event) { success, error in
}
}
func todaysEvents() {
let calendar = Calendar.autoupdatingCurrent
let startDate = Date.now
var onDayComponents = DateComponents()
onDayComponents.day = 1
let endDate = calendar.date(byAdding: onDayComponents, to: .now)!
let predicate = store.predicateForEvents(withStart: startDate, end: endDate, calendars: nil)
events = store.events(matching: predicate)
}
}
import EventKit
import SwiftUI
struct ContentView: View {
@StateObject var store = EventKitManager()
var body: some View {
Text("\(store.events.count)")
}
}
I'm trying to use EventKit with SwiftUI in order to get a simple count of scheduled events on the users iOS calendar. I have added Privacy - Calendars Usage Description to the Info.plist file with a value.
Here's my code. I think something is wrong with the startDate in the predicate... but no matter what I have tried my count of var events:[EKEvent] always comes back as 0. I should add that I have also added a number of events on the simulator's calendar each day I am trying to get this to work. Any help you can provide is greatly appreciated!!!!
import EventKit
import Foundation
import SwiftUI
class EventKitManager: ObservableObject {
var store = EKEventStore()
var events: [EKEvent] = []
init() {
requestAccessToCalendar()
todaysEvents()
}
func requestAccessToCalendar() {
store.requestAccess(to: .event) { success, error in
}
}
func todaysEvents() {
let calendar = Calendar.autoupdatingCurrent
let startDate = Date.now
var onDayComponents = DateComponents()
onDayComponents.day = 1
let endDate = calendar.date(byAdding: onDayComponents, to: .now)!
let predicate = store.predicateForEvents(withStart: startDate, end: endDate, calendars: nil)
events = store.events(matching: predicate)
}
}
import EventKit
import SwiftUI
struct ContentView: View {
@StateObject var store = EventKitManager()
var body: some View {
Text("\(store.events.count)")
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
谢谢@jnpdx!我找到了解决方案。以下代码有效 - 您必须在 requestAccessToCalendar 调用中重新初始化商店,当然还要使用 @Published 包装器...我不敢相信我错过了! :]
Thanks @jnpdx! I found a solution. The following code works - you have to reinitialize the store in the requestAccessToCalendar call and of course use the @Published wrapper... I can't believe I missed that! : ]