I am working with Screen Time API to get the usage duration of the selected apps installed in the iPhone.
My app only shows 0s (zero second) on the screen. But it should show the usage duration of the selected app. I am selecting app using familyActivityPicker.
I am passing the token of applications to the filter by selecting it using familyActivityPicker. But it shows 0s always. I added the Device Activity Report Extension to the project to get the report. How can I get app wise usage duration ?
`import SwiftUI
import FamilyControls
import DeviceActivity
@main
struct DeviceActivityTrackerApp: App {
let center = AuthorizationCenter.shared
@State private var context: DeviceActivityReport.Context = .init(rawValue: "Total Activity")
@State var filter = DeviceActivityFilter()
@State var isPresented = false
@State var selection = FamilyActivitySelection()
@State private var refresh = false
var body: some Scene {
WindowGroup {
VStack {
// Select app
Spacer()
Button("Select Any app") { isPresented = true }
.familyActivityPicker(isPresented: $isPresented,
selection: $selection)
.onChange(of: selection) { newSelection in
let applications = selection.applicationTokens
let categories = selection.categoryTokens
let webDomains = selection.webDomainTokens
self.filter = DeviceActivityFilter(
segment: .daily(
during: Calendar.current.dateInterval(
of: .weekOfYear, for: .now
)!
),
users: .all,
devices: .init([.iPhone, .iPad]),
applications: applications,
categories: categories,
webDomains: webDomains
)
}
Spacer()
DeviceActivityReport(context, filter: filter)
}
.padding(50)
.onAppear {
Task {
do {
try await center.requestAuthorization(for: .individual)
} catch {
print("Failed to enroll user with error: \(error)")
}
}
}
}
}
}`
