'SwiftUI - Accessing EventKitStore and store.events(matching:...)

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)")
    }
}


Solution 1:[1]

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! : ]

import EventKit
import Combine
import Foundation
import SwiftUI

class EventKitManager: ObservableObject {
    
    var store = EKEventStore()
    @Published var events: [EKEvent] = []

    
    init() {
        requestAccessToCalendar()
        todaysEvents()
  
    }
    
    func requestAccessToCalendar() {
        store.requestAccess(to: .event) { success, error in
            self.store = EKEventStore()

        }
    }
    

    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)
        
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sans connaissance