Device Activity

RSS for tag

Monitor web and app usage through custom time windows and events.

Posts under Device Activity tag

89 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Device Activity Report Not showing any information
All After about 20 hours straight of working on this and having scrapped it twice I am realizing I should have asked everyone here for help. I am just trying to get device activity report extension to work inside an existing app. I have been heavily using family controls, managedsettings and deviceactivity and decided it would be nice to output some of the app usage so the User (parent) can see their children's app usage. I installed the target via xcode, confirmed group names match, and think I have it embedded correctly but when I run the app and call the view within the extension to show minutes used by any apps it just shows no time has been used. In addition, when I put print statements into the extension they do not show up in console. I have confirmed the main app target->Build phases->Link binary with Libraries has: ManagedSettings.framework FamilyControls.Framework DeviceActivity.framework I have confirmed in xcode that the main app target->Build phases -> Embed Foundation Extensions has: ShieldConfiguration.appex ShieldActionExtension.appex DeviceActivityMonitor.appex I have confirmed in xcode that the main app target->Build phases-> Embed ExtensionKit Extensions has: UsageReportExtension.appex I have used the apps I am trying to show data for extensively in the last 36 hours. Here is my UsageReportExtension info.plist EXAppExtensionAttributes EXExtensionPointIdentifier com.apple.deviceactivityui.report-extension .entitlement com.apple.developer.family-controls com.apple.security.application-groups group.com.jrp.EarnYourTurnMVP2.data Here is the file in the app (timebankview.swift) calling the extension/showing the extension view(AppUsageReportView.swift) import DeviceActivity import ManagedSettings struct TimeBankView: View { @EnvironmentObject private var appState: AppState @State private var reportInterval: DateInterval = { let calendar = Calendar.current let now = Date() let yesterdayDate = calendar.date(byAdding: .day, value: -1, to: now) ?? now return DateInterval(start: yesterdayDate, end: now) }() private var reportFilter: DeviceActivityFilter { let selection = appState.screenTimeController.currentSelection return DeviceActivityFilter( segment: .daily(during: reportInterval), users: .children, devices: .all, applications: selection.applicationTokens, categories: selection.categoryTokens // webDomains: selection.webDomains // Add if needed ) } var body: some View { ZStack { Color.appTheme.background(for: appState.isParentMode) .edgesIgnoringSafeArea(.all) ScrollView { VStack(spacing: 20) { Text("Time Bank") DeviceActivityReport(.childUsageSummary, filter: reportFilter) Here is AppUsageReportView.swift import SwiftUI struct AppUsageReportView: View { let config: DetailedAppUsageConfiguration // Use the detailed config var body: some View { VStack { Text("App Usage Details") Text("Total Screen Time: \(config.totalDurationFormatted)") if config.applicationsUsed.isEmpty { Text("No specific app usage data available for the selected period/filter.") } else { Text("Apps Used:") List { ForEach(config.applicationsUsed) { appInfo in HStack { Image(systemName: "app.dashed") Text(appInfo.appName) .lineLimit(1) Text(appInfo.durationFormatted) Here is AppUsageReportScene.swift: import SwiftUI import ManagedSettings struct AppInfo: Identifiable, Hashable { let id = UUID() let appName: String let durationFormatted: String } struct DetailedAppUsageConfiguration { var totalDurationFormatted: String = "Calculating..." var applicationsUsed: [AppInfo] = [] } struct AppUsageReportScene: DeviceActivityReportScene { let context: DeviceActivityReport.Context = .childUsageSummary let content: (DetailedAppUsageConfiguration) -> AppUsageReportView func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> DetailedAppUsageConfiguration { var config = DetailedAppUsageConfiguration() var appDurations: [String: TimeInterval] = [:] var totalAggregatedDuration: TimeInterval = 0 let formatter = DateComponentsFormatter() formatter.allowedUnits = [.hour, .minute, .second] formatter.unitsStyle = .abbreviated formatter.zeroFormattingBehavior = .pad var segmentCount = 0 var categoryCount = 0 var appCount = 0 for await activityData in data { // Check segments var tempSegmentCount = 0 for await segment in activityData.activitySegments { segmentCount += 1 tempSegmentCount += 1 totalAggregatedDuration += segment.totalActivityDuration var tempCategoryCount = 0 for await categoryActivity in segment.categories { categoryCount += 1 tempCategoryCount += 1 var tempAppCount = 0 for await appActivity in categoryActivity.applications { appCount += 1 tempAppCount += 1 let appName = appActivity.application.localizedDisplayName ?? "Unknown App" let duration = appActivity.totalActivityDuration appDurations[appName, default: 0] += duration }}} } config.totalDurationFormatted = formatter.string(from: totalAggregatedDuration) ?? "N/A" config.applicationsUsed = appDurations .filter { $0.value >= 1 .map { AppInfo(appName: $0.key, durationFormatted: formatter.string(from: $0.value) ?? "-") } .sorted { lhs, rhs in let durationLHS = appDurations[lhs.appName] ?? 0 let durationRHS = appDurations[rhs.appName] ?? 0 return durationLHS > durationRHS } if !config.applicationsUsed.isEmpty { for (index, app) in config.applicationsUsed.enumerated() { } } else { } return config }} UsageReportExtension.swift struct UsageReportExtension: DeviceActivityReportExtension { init() { print("🚀 [UsageReportExtension] Extension initialized at \(Date())") print("🔍 [UsageReportExtension] Process info: \(ProcessInfo.processInfo.processName) PID: \(ProcessInfo.processInfo.processIdentifier)") } var body: some DeviceActivityReportScene { let _ = print("📊 [UsageReportExtension] Building report scenes at \(Date())") TotalActivityReport { totalActivity in print("🕰️ [TotalActivityReport] Creating view with data: \(totalActivity)") return TotalActivityView(totalActivity: totalActivity) }}}
1
0
29
5d
iOS 18.4 (?) FamilyActivityPicker regression: presenting SFSafariViewController on top bugs
If I present "SFSafariViewController" when a "FamilyActivityPicker" is visible, it will automatically dismiss the "SFSafariViewController" and crash the "FamilyActivityPicker." I'm assuming the cause of the bug is that each is in a separate process (aside from the app), and there's some hacks to try to stop "FamilyActivityPicker" from crashing, and this is causing the new bug because "SFSafariViewController" is also in a separate process. (I'm not 100% if its just in 18.4 or iOS 18 overall...) (I'll try to file a feedback soon, but its 100% reproducible for me across multiple devices on iOS 18.4)
6
0
61
1w
Device Activity Monitor Schedules Disappear
Hey everyone, I have an app using the screen time api, I've had quite a few reports from users saying that our monitoring features stop working until they open our app. What happens is that activities and schedules set with the device activity monitor seem to disappear. This is something we check on app re-opens and so we schedule them again and that is why the monitoring starts working again. Of course our current solution is not optimal since our app is mainly passive. Has anyone experienced these kinds of issue ?
0
1
36
3w
FamilyControls Framework info.plist missing
We are trying to create a screentime app using the Family Controls as well as Device activity frameworks. The build succeeds but while pushing to an iphone we are getting an info.plist file for deviceactivity.framework could not be found error. For reference when using the Screentime API a physical device must be used not a simulator. When we remove the device activity framework this error also occurs for the family controls framework. We have added the Family Controls(development) Capability and applied for the distribution capability. We have redownloaded xcode multiple times on the main device, deleted derived data, and redownloaded all of the iphone SDKs and the issue still persists.
0
0
183
Mar ’25
Is it work startMonitoring from DeviceActivityMonitorExtension's eventDidReachThreshold function?
I want to monitor again from the bellow function of DeviceActivityMonitorExtension. I have the function of startMonitoring like this. override func eventDidReachThreshold(_ event: DeviceActivityEvent.Name, activity: DeviceActivityName) { super.eventDidReachThreshold(event, activity: activity) startMonitoring() } public func startMonitoring() { let startTime = DateComponents(hour: 0, minute: 0, second: 0) let endTime = DateComponents(hour: 23, minute: 59, second: 59)//DateComponents(hour: 11, minute: 0, second: 0)// let schedule = DeviceActivitySchedule( intervalStart: startTime,//DateComponents(hour: 0, minute: 0, second: 0), intervalEnd: endTime, repeats: true //warningTime: DateComponents(minute:1) ) let selection: FamilyActivitySelection = savedSelection() ?? FamilyActivitySelection() let center = DeviceActivityCenter() let selections = self.savedSelection() ?? FamilyActivitySelection() let applications = selections.applicationTokens let categories = selections.categoryTokens let webCategories = selections.webDomainTokens let store = ManagedSettingsStore() store.shield.applicationCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set()) store.shield.applications = applications store.shield.webDomains = webCategories let scheduleHard = DeviceActivitySchedule( intervalStart: startTime,//DateComponents(hour: 0, minute: 0, second: 0), intervalEnd: endTime, repeats: true //warningTime: DateComponents(minute:1) ) let event = DeviceActivityEvent( applications: selection.applicationTokens, categories: selection.categoryTokens, webDomains: selection.webDomainTokens, threshold: DateComponents(minute: 0)//timeLimitToUseApp i.e for 15 mins ) do { try center.startMonitoring( .weekend, during: scheduleHard, events: [ .weekend: event, ] ) print("ScreenTime Monitoring Started") } catch let error { print(error.localizedDescription) } } Please provide us with a solution about starting monitoring from DeviceActivityMonitoringExtension's eventDidReachThreshold function or if there is any other way.
0
0
225
Mar ’25
Using Device Data for Finger Printing
Our business model is to identify Frauds using our advanced AI/ML model. However, in order to do so we need to collect many device information which seems to be ok according to https://developer.apple.com/app-store/user-privacy-and-data-use/ But it's also prohibited to generate a fingerprint, so I need more clarification here. Does it mean I can only use the data to identify that a user if either fraud or not but I cannot generate a fingerprint to identify the device? If so, I can see many SKD in the market that generates Fingerprints like https://fingerprint.com/blog/local-device-fingerprint-ios/ and https://shield.com/?
1
0
347
3w
Unblocking Apps After a Scheduled Duration in FamilyControl
I am able to block apps using FamilyControl and Shield. Unblocking is also simple—just assign nil to store.shield.applications. However, I want to unblock them even when the app is not open. Use case: Let's say the app allows users to create a session where a particular app is blocked for a specific duration. Once the session starts, the app should remain blocked, and as soon as the session time ends, it should automatically be unblocked. Please help me with this. Thank you!
0
0
326
Feb ’25
How to remotely disable or block apps on a child’s device using FamilyControls and DeviceActivity API?
After reading Apple documentation (FamilyControls, DeviceActivity, ManagedSettings, ManagedSettingsUI, ScreenTime) and testing the API, I do not find a way to get the child's device apps on the parent device in order to block them or disable them for a certain time. Is there a way of doing it? Or can it only be done locally on the child device?
2
0
372
Mar ’25
DeviceActivityMonitor.intervalDidEnd never getting called
I'm trying to build an app with a DeviceActivityMonitor extension that executes some code after 15 minutes. I can confirm that the extension is set up correctly and that intervalDidStart is executed, but for some reason the intervalDidEnd method never gets called. What I'm doing in both is just registering a local notification. class DeviceActivityMonitorExtension: DeviceActivityMonitor { let store = ManagedSettingsStore() override func intervalDidStart(for activity: DeviceActivityName) { createPushNotification( title: "Session activated!", body: "" ) super.intervalDidStart(for: activity) } override func intervalDidEnd(for activity: DeviceActivityName) { createPushNotification( title: "Session ended", body: "" ) super.intervalDidEnd(for: activity) } private func createPushNotification(title: String, body: String) { let content = UNMutableNotificationContent() content.title = title content.body = body // Configure the recurring date. var dateComponents = Calendar.current.dateComponents([.era, .year, .month, .day, .hour, .minute, .second], from: Date().addingTimeInterval(1.0)) dateComponents.calendar = Calendar.current dateComponents.timeZone = TimeZone.current // Create the trigger as a repeating event. let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) let uuidString = UUID().uuidString let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger) // Schedule the request with the system. let notificationCenter = UNUserNotificationCenter.current() notificationCenter.add(request) } } And this is the method that is starting the monitoring session: @objc public static func startSession() -> String? { // Calculate start and end times let center = DeviceActivityCenter() let minutes = 15 let startDate = Date().addingTimeInterval(1) guard let endDate = Calendar.current.date(byAdding: .minute, value: minutes, to: startDate) else { return "Failed to create end date?" } // Create date components and explicitly set the calendar and timeZone let startComponents = Calendar.current.dateComponents([.era, .year, .month, .day, .hour, .minute, .second], from: startDate) let endComponents = Calendar.current.dateComponents([.era, .year, .month, .day, .hour, .minute, .second], from: endDate) // Create schedule let schedule = DeviceActivitySchedule( intervalStart: startComponents, intervalEnd: endComponents, repeats: false ) print("Now", Date()) print("Start", startDate, startComponents) print("End", endDate, endComponents) print(schedule.nextInterval) do { // Use a consistent activity name for our simple implementation let activity = DeviceActivityName("SimpleSession") try center.startMonitoring(activity, during: schedule) return nil } catch { return "Failed to start monitoring: \(error)" } } I can confirm my dates & date components make sense with the 4 print statements. Here is the output: Now 2025-02-12 04:21:32 +0000 Start 2025-02-12 04:21:33 +0000 era: 1 year: 2025 month: 2 day: 11 hour: 20 minute: 21 second: 33 isLeapMonth: false End 2025-02-12 04:36:33 +0000 era: 1 year: 2025 month: 2 day: 11 hour: 20 minute: 36 second: 33 isLeapMonth: false Optional(2025-02-12 04:21:33 +0000 to 2025-02-12 04:36:33 +0000) I get the Session activated! notification but never get the Session ended notification. Half an hour later, I've tried debugging the DeviceActivityCenter by printing out the activities property and can see that it is still there. When I try to print out the nextInterval property on the schedule object i get from calling center.schedule(for:), it returns nil. I'm running this on an iPhone 8 testing device with developer mode enabled. It has iOS 16.7.10. I'm totally lost as to how to get this to work.
1
0
283
Feb ’25
About the problem that DeviceActivityMonitorExtension does not work
I am developing an app that can help users disable selected apps at a specified time, so that users can get away from their phones and enjoy real life. Here is my data structure: extension ActivityModel { @NSManaged public var id: UUID @NSManaged public var name: String @NSManaged public var weeks: Data @NSManaged public var weekDates: Data @NSManaged public var appTokens: Data } Among them, weeks is of [Bool] type, indicating which weeks from Sunday to Saturday are effective; weekDates is of [[Date,Date]] type, indicating the effective time period; appTokens is of Set type, indicating the selected apps。 At the beginning, I will open a main monitor: let deviceActivityCenter = DeviceActivityCenter() do{ try deviceActivityCenter.startMonitoring( DeviceActivityName(activityModel.id), during: DeviceActivitySchedule( intervalStart: DateComponents(hour: 0,minute: 0,second: 0), intervalEnd: DateComponents(hour: 23,minute: 59,second: 59), repeats: true ) ) }catch { return false } Since the time range may be different every day, I will start the sub-monitoring of the day every time the main monitoring starts: override func intervalDidStart(for activity: DeviceActivityName) { super.intervalDidStart(for: activity) if activity.rawValue.hasPrefix("Sub-") { ActivityModelManager.disableApps( Tools.getUUIDFromString(activity.rawValue) ) return } let weekIndex = Calendar.current.component(.weekday, from: .now) let weeks = ActivityModelManager.getWeeks(activity.rawValue) if weeks[weekIndex] { let weekDates = ActivityModelManager.getWeekDates(activity.rawValue) let deviceActivityCenter = DeviceActivityCenter() do{ try deviceActivityCenter.startMonitoring( DeviceActivityName("Sub-" + activityModel.id), during: DeviceActivitySchedule( intervalStart: getHourAndMinute(weekDates[weekIndex][0]), intervalEnd: getHourAndMinute(weekDates[weekIndex][1]), repeats: false ) ) }catch { return } }esle { return } } I will judge whether it is main monitoring or sub monitoring based on the different activity names. When the sub-monitor starts, I will get the bound application and then disable it: static func disableApps(_ id : UUID){ let appTokens = ActivityModelManager.getLimitAppById(id) let name = ManagedSettingsStore.Name(id.uuidString) let store = ManagedSettingsStore(named: name) store.shield.applications = appTokens return } When the child monitoring is finished, I resume the application: static func enableApps(_ id : UUID){ let name = ManagedSettingsStore.Name(id.uuidString) let store = ManagedSettingsStore(named: name) store.shield.applications = [] } The above is my code logic. When using DeviceActivityMonitorExtension, I found the following problems: intervalDidStart may be called multiple times, resulting in several sub-monitors being started. After a period of time, the monitoring is turned off. The static methods enableApps and disableApps are sometimes not called
4
0
485
Mar ’25
DeviceActivityReport view fails to render until it's repeatedly added to the view hierarchy
The DeviceActivityReport view does not render immediately when added to the view hierarchy. Instead, it requires repeated navigation to the screen hosting the DeviceActivityReport view for it to appear. Furthermore, there is no programmatic way to determine whether the view is being rendered for the user, leading to an inconsistent and often poor user experience. I've created a sample project that demonstrates the issue.
2
0
329
Mar ’25
Allowing workaround for FamilyActivityPicker crash
As discussed and acknowledged here, there is a known bug with the FamilyActivityPicker. When a user expands a category that contains enough tokens to exceed the 50mb memory limit, the FamilyActivityPicker crashes. This happens quite frequently for heavy Safari users. An apple engineer mentioned on this thread that WebDomains shown in the picker are present based on the last 30 days of usage data as surfaced by WebKit. Is there any way a user can clear these WebDomains? Either programatically through our app or any other process we can guide them to as a workaround while this issue is getting fixed?
0
2
341
Jan ’25
DeviceActivityReport fails to display SceneView
I am trying to return a SceneView from a DeviceActivityReport. I have my DeviceActivityReportExtension correctly set up and I am able to display a view with text or other UI elements in it, but attempting to return a SceneView as part of the body just won't display. I have this example. When I display this SceneView in my main app, it displays correctly. When I put the same code inside the DeviceActivityReportExtension, the scene does not show up and an error failed to create a gl context appears repeatedly in the console. I'm pretty stumped and would appreciate any suggestions. import SwiftUI import SceneKit struct TestScene: View { var scene: SCNScene? { SCNScene(named: "art.scnassets/environment.scn") } var cameraNode: SCNNode? { let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(x: 0, y: 0, z: 2) return cameraNode } var body: some View { SceneView( scene: scene, pointOfView: cameraNode, options: [ .allowsCameraControl, .autoenablesDefaultLighting, .temporalAntialiasingEnabled ] ) } }
2
0
361
Jan ’25
DeviceActivityMonitor extension does not call back at the set time
Hello Apple development team, I have developed an App for screen time management, which mainly uses ScreenTimeAPI. Users can set certain Apps to be disabled during a certain period of time. After the App is released, users often report that the settings do not take effect as expected. I have seen many developers on the forum reporting that the DeviceActivityMonitor extension sometimes does not trigger callbacks. Based on this background, I have the following questions: Is it a known problem that the DeviceActivityMonitor extension sometimes does not trigger callbacks? If so, are there any means to avoid or reduce the probability of occurrence? In addition to being killed by the system when the running memory exceeds (I just called some ScreenTimeAPI and accessed UserDefaults in the extension, which should not exceed the running memory), under what other circumstances will the DeviceActivityMonitor extension be killed by the system? Will it automatically recover after being killed? Will some callbacks be called when killing? Does ManagedSettingsStore have a life cycle? How do you avoid conflicts when configuring the underlying operating mechanism of multiple stores? This is a random problem. I have never encountered it during development and debugging, but users often report it. thanks
1
0
373
Feb ’25
Provisioning Profile Error
I'm building an app that uses the Screen Time API and DeviceActivityMonitoring Framework. It works when I run the simulator build on iPhone 16 but when I try to launch it on my own iPhone, I get these errors. Provisioning profile "iOS Team Provisioning Profile: Kanso- Digital-Wellness.Kanso-v2" doesn't include the com.apple.developer.device-activity.monitoring entitlement. KansoMonitorExtension 1 issue x Provisioning profile "iOS Team Provisioning Profile: Kanso-Digital-Wellness.Kanso-v2.KansoMonitorExtension" doesn't include the com.apple.developer.device-activity.monitoring en... Read something online that said a reboot would fix this, but I tried and no luck. Any ideas? I'm not very technical, so would pay someone to fix this for me :)
1
0
448
Jan ’25
Problem with DeviceActivitySchedule and DeviceActivityMonitor
Hey, I’m having some issues with DeviceActivitySchedule and DeviceActivityMonitor. I want to create a schedule that blocks apps (by family control) when it starts. However, even when the schedule is supposed to start on this iPhone, nothing happens, and no logs are being recorded main target: // TestView_.swift // Sloth // // Created by on 11/01/2025. // import SwiftUI import DeviceActivity import FamilyControls import ManagedSettings struct TestView_: View { var body: some View { VStack(spacing: 20) { Text("Test DeviceActivityMonitor") .font(.title) Button("Start test mon") { let now = Date() let start = Calendar.current.date(byAdding: .minute, value: 2, to: now)! let end = Calendar.current.date(byAdding: .minute, value: 20, to: now)! print("thd") DeviceScheduleTester().scheduleTestActivity(startDate: start, endDate: end) } } .padding() } } extension DeviceActivityName { static let daily = DeviceActivityName("daily") } DeviceActivityMonitor: class DeviceScheduleTester { private let center = DeviceActivityCenter() func scheduleTestActivity(startDate: Date, endDate: Date) { let calendar = Calendar.current let startComponents = calendar.dateComponents([.hour, .minute], from: startDate) let endComponents = calendar.dateComponents([.hour, .minute], from: endDate) // Tworzymy schedule let schedule = DeviceActivitySchedule( intervalStart: startComponents, intervalEnd: endComponents, repeats: true ) do { try center.startMonitoring(.daily, during:schedule) print("startMonit /(\(schedule))") } catch { print("ghfgh") } } } struct TestView__Previews: PreviewProvider { static var previews: some View { TestView_() } } DeviceActivityMonitor target: // BlockingAppsMonitorExtension // // Created by on 10/01/2025. import DeviceActivity import FamilyControls import ManagedSettings import os let logger = Logger() public class BlockingAppsMonitor: DeviceActivityMonitor { private let store = ManagedSettingsStore() public override func intervalDidStart(for activity: DeviceActivityName) { super.intervalDidStart(for: activity) print("Rozpoczęcie interwału blokowania \(activity.rawValue)") logger.info("intervalDidStart") startBlocking() } public override func intervalDidEnd(for activity: DeviceActivityName) { super.intervalDidEnd(for: activity) print("Zakończenie interwału blokowania \(activity.rawValue)") logger.info("intervalDidend") stopBlocking() } @discardableResult private func startBlocking() -> Int { print("number of unique apps") return 51 store.shield.applicationCategories = .all() // return exceptions.count } private func stopBlocking() { store.shield.applicationCategories = nil store.shield.applications = nil } } INB4: In both files are added family controls Secent file is added in DeviceActivityMonitor target. Apple answer please?
1
0
418
Jan ’25
DeviceActivityReportExtension / ScreenTimeBriefReport does not localize strings
Hello, In one of our apps we use DeviceActivityReportExtension to show the user how much screen time is remaining. The calculation is working as expected, but we have noticed that the labels in our ScreenTimeBriefReport are not localized to the device language. Example: Device with language set to Swedish App fully translated to English and Swedish Result: All labels in app are using the Swedish translations, except the strings in our ScreenTimeBriefReport instance. These labels are using the English localization. I've verified it's using the English localization from our Localizable.xcstrings file. I tried logging device language from our ScreenTimeBriefReport instance, but I could not see anything in Console.app. I guess this is intentional so no sensitive user information can be extracted. Is this a known feature or bug? If it's the latter, is there a known workaround? Sincerely, César
1
0
466
Jan ’25