I use DeviceActivityCenter to monitor app usage. For DeviceActivityEvent, I set 30 events, and the threshold of each event increases by 2 minutes:
var events: [DeviceActivityEvent.Name: DeviceActivityEvent] = [:]
for index in 0..<30 {
let threshold = (index == 29)
? DateComponents(hour: 1)
: DateComponents(minute: (index + 1) * 2)
let name = DeviceActivityEvent.Name("\(prefix)|\(index)")
events[name] = DeviceActivityEvent(applications: tokens, threshold: threshold)
}
After reaching the last DeviceActivityEvent, I will restart directly in DeviceActivityMonitor
private func restartMonitoring(activity: DeviceActivityName) {
let center = DeviceActivityCenter()
let currentEvents = center.events(for: activity)
do {
try center.startMonitoring(activity, during: schedule, events: currentEvents)
} catch {
print("Fail: \(error)")
}
}
But I found that after restarting, DeviceActivityEvent will be automatically executed even if I don't use the app.
My iOS version is 18.5