I’m trying to create a function in Swift that requests the authorization for the individual and fetch the screen time app usage data of all the installed apps inside iphone device for last 24 hours. I’ve added the necessary permissions and capabilities.
This is my code:
import UIKit
import DeviceActivity
import FamilyControls
func requestScreenTimeData() {
Task {
do {
try await AuthorizationCenter.shared.requestAuthorization(for: .individual)
print("Authorization successful!")
// Define the filter for activity monitoring
let endDate = Date() // Current time
let startDate = Calendar.current.date(byAdding: .hour, value: -24, to: endDate)!
let dateInterval = DateInterval(start: startDate, end: endDate)
let activityFilter = DeviceActivityFilter(
segment: .daily(during: dateInterval),
users: .all,
devices: .init([.iPhone])
)
// Fetch and return the app usage data
} catch {
print("Authorization failed with error: (error.localizedDescription)")
}
}
}
I want to get this data in json or similar form so that i can show it inside my customized UI view.
1