Device Activity

RSS for tag

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

Posts under Device Activity tag

92 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

DeviceActivityMonitor event threshold callbacks often triggered multiple times in a row
My app sends screen time awareness notifications based on DeviceActivityMonitor thresholds. Often, users receive two notifications in a row for the same screen time threshold. This means that the app extension is triggering the same eventDidReachThreshold callback function twice for the same threshold. I've made sure that there is only one activity schedule being monitored. This happens often, but not every time (over 50% of the time). Anybody else experience this issue, and any way to mitigate it?
3
0
885
Jan ’24
Issue with DeviceActivityMonitor - eventDidReachThreshold Callback Not Triggering Properly
Hello, I'm currently experiencing an issue with the DeviceActivityMonitor extension in my code, specifically with the eventDidReachThreshold callback. I'm hoping to get some insights into why this problem occurs and how to resolve it. Problem: Issue 1: The eventDidReachThreshold callback is not triggering as expected. It appears that the callback is not being invoked when the threshold is reached. Issue 2: After a few seconds, the eventDidReachThreshold callback starts to trigger multiple times. This unexpected behavior is causing problems in my code, as it results in incorrect actions being taken. iOS version: iOS16.7.2 and iOS17.1 Xcode version: 15.0.1 Swift version: 5.9 Here is my code to start the monitoring: func startMonitoring() { var startTime : DateComponents = DateComponents(hour: 0, minute: 0) let endTime : DateComponents = DateComponents(hour: 23, minute: 59) /// Creates the schedule for the activity, specifying the start and end times, and setting it to repeat. let schedule = DeviceActivitySchedule(intervalStart: startTime, intervalEnd: endTime, repeats: true, warningTime: nil) /// Defines the event that should trigger the encouragement. let event = DeviceActivityEvent(applications: socialActivitySelection.applicationTokens, categories: socialActivitySelection.categoryTokens, webDomains: socialActivitySelection.webDomainTokens, threshold: DateComponents(minute: 2)) let events: [DeviceActivityEvent.Name: DeviceActivityEvent] = [.socialScreenTimeEvent : event] do { activityCenter.stopMonitoring([.socialScreenTime]) /// Tries to start monitoring the activity using the specified schedule and events. try activityCenter.startMonitoring(.socialScreenTime, during: schedule, events: events) } catch { /// Prints an error message if the activity could not be started. print("Could not start monitoring: \(error)") } } If there are any known workarounds or potential solutions, please share them. Thank you for your help in resolving this problem.
0
0
438
Nov ’23
Analytics events not triggering with DeviceActivityMonitor app extension on iOS 17
I'm encountering a problem with the DeviceActivityMonitor framework on iOS 17 that wasn't present in iOS 16. The app extension sends analytics events via the Segment SDK whenever the extension's functions are called. This setup worked flawlessly on iOS 16. However, since upgrading to iOS 17, it appears that the vast majority of my iOS 17 users are not triggering the expected analytics events. I'm aware that network requests in app extensions are not officially supported, yet somehow, Segment's SDK managed to function without issues in the previous OS version. Could there have been any changes in iOS 17 related to app extensions or the DeviceActivityMonitor framework that might be influencing this change in analytics behavior? Or perhaps there's a new restriction or modification in the app extension's network capabilities that I might be overlooking? Any insights into these changes or guidance on how to ensure analytics events are triggered reliably within the app extension on iOS 17 would be greatly appreciated. Thank you in advance for your help!
0
1
417
Nov ’23
DeviceActivityReportExtension working on IOS 17 device but not on IOS 16 device
When I run it on my IOS 16 device I get this error message. When I run it on my device with IOS 17 I get none of these logs. My build target for both the widget and app are 16.0. "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=66, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler} 2023-10-19 13:49:44.565845-0400 Halo[87980:7963095] [db] Failed to initialize client context with error Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=66, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler} 2023-10-19 13:49:44.569345-0400 Halo[87980:7963095] Metal API Validation Enabled
2
1
455
Oct ’23
DeviceActivityMonitor extension not running on device?
Hello friends, I am working on an iOS app that uses the ScreenTime API to monitor app usage on the user's device. I am able to set up the monitoring schedule and start monitoring using code like this in the application: var calendar = Calendar.current let startDateComps = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: startDate) let endDateComps = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: endDate) let schedule = DeviceActivitySchedule(intervalStart: startDateComps, intervalEnd: endDateComps, repeats: false) let sessionName = DeviceActivityName(String(session.id)) do { try self.center.startMonitoring(sessionName, during: schedule) } catch { print("Could not start monitoring session \(sessionName): \(error)") } This appears to work. But in the DeviceActivityMonitor extension that I've added to the project, I never seem to get the init or intervalDidStart calls, and when I specify the DeviceActivityMonitor extension's scheme and try to debug it, XCode never seems to be able to attach to the DeviceActivityMonitor extension process (it shows "Waiting to attach" in the Debug navigator but never attaches), and I can't find the extension process when I manually try to attach to the process on the device. I understand that the extension process isn't necessarily running all the time, but shouldn't we at least get the init call? I think the extension was added to the project correctly, it shows up as a separate target in the project and also as an embedded appex in the main app target, and under the "Embed Foundation Extensions" build phase with the destination "Plugins and Foundation Extensions." I also added the extension and the main app to the same app group. Also when I monitor the device I'm using for testing using the console, I don't see any mention of the DeviceActivityMonitor extension after the messages from installcoordinationd at install time. Does anyone have any suggestions for how I could trouble-shoot this and figure out why the extension isn't running on the device?
1
0
500
Oct ’23
DeviceActivityReport Formatting
Hello everyone, I'm currently developing an app that requires Device activity report to be displayed at the click of a button. I'm having an issue where when the button is clicked and the Device activity report is displayed it pushes all other elements away from it. Is this a feature and do I need to configure this specifically with a ZStack? Or am I doing something wrong on my end? Thanks!
0
0
289
Oct ’23
Critical Bug in Screen Time Frameworks – User's Phone Rendered Unusable
Hello Apple Developer Community, We're experiencing a critical issue with the Screen Time frameworks, and it's affecting one of our users severely. I'm hoping someone here can provide guidance or a potential solution. Details: Our app offers a feature using the ManagedSettings shield that lets users block all apps based on a set schedule. After the scheduled block ends, the apps are expected to become accessible again. In one case, a user reported that the apps did not unblock after the schedule ended. Upon trying to manually end the session from within our app, the app only displays a blank white screen. The user attempted to disable Screen Time access for our app via the iOS settings, but the apps remained blocked. Even after completely disabling Screen Time from the settings or restarting the phone, the apps stayed blocked. Interestingly, I attempted to replicate the issue on my end by toggling Screen Time settings and restarting, but everything worked as expected and I could not reproduce the problem. This issue, though seemingly isolated, has rendered a user's phone virtually unusable, and highlights a potential high-impact bug within the Screen Time framework. It feels necessary for there to be a "master off-switch" or a fail-safe mechanism in these scenarios. Any insights, solutions, or workarounds would be deeply appreciated. It's crucial for us to support our user and resolve this promptly. Thank you in advance!
8
1
1.3k
Dec ’23
DeviceActivityReport no longer works on iOS 16 with Xcode 15
Hello, we had working DeviceActivityReport in our app for months now. However when building with Xcode 15 (previously betas, now the GM), the activity reports no longer displays anything on iOS 16 devices. If we run it with Xcode 14, it works. But with Xcode 15 builds, the device activity report only works on iOS 17 devices :( I am able to see some somewhat generic errors in the Console.app when opening screen that contains the report. -[_EXServiceClient launchWithConfiguration:error:]_block_invoke failed with error: Error Domain=com.apple.extensionKit.errorDomain Code=2 UserInfo={NSUnderlyingError=0x280b9b600 {Error Domain=RBSRequestErrorDomain Code=5 UserInfo={NSLocalizedFailureReason=<private>}}} Failed to create extensionProcess for extension '<private>' error: Error Domain=com.apple.extensionKit.errorDomain Code=2 UserInfo={NSUnderlyingError=0x280b9b600 {Error Domain=RBSRequestErrorDomain Code=5 UserInfo={NSLocalizedFailureReason=<private>}}}. Failed to make extensionProcess with error: Error Domain=com.apple.extensionKit.errorDomain Code=2 UserInfo={NSUnderlyingError=0x280b9b600 {Error Domain=RBSRequestErrorDomain Code=5 UserInfo={NSLocalizedFailureReason=<private>}}} Failed to get extension process and XPC endpoints with error: Error Domain=com.apple.extensionKit.errorDomain Code=2 UserInfo={NSUnderlyingError=0x280b9b600 {Error Domain=RBSRequestErrorDomain Code=5 UserInfo={NSLocalizedFailureReason=<private>}}} And I managed to find one error that is specific to our activity extension which says just: Cannot track instance that is already dead!
3
3
970
Sep ’23
Monitoring Connection Status to a DeviceActivityReport App Extension
Hello, I've been working with an app that leverages a DeviceActivityReport app extension. I want to ensure that the main app can gracefully handle scenarios where the connection to the app extension might get terminated unexpectedly. Can anyone guide me on how to detect from the main app when the connection to the app extension gets terminated? I believe being able to detect this would allow for better error handling and potentially reduce instances where the UI appears blank due to a lost connection. Thank you for any insights or advice on this topic.
1
1
418
Sep ’23
`eventDidReachThreshold` Not Triggering Consistently in Device Activity Monitor Extension
Hello everyone 👋 I wanted to discuss an issue that has always been somewhat present, but seems to have become more frequent since the latest iOS 17 versions. When scheduling an activity that includes an event, the eventDidReachThreshold method does not trigger consistently within the device activity monitor extension. The issue is intermittent. However, repeating the following procedure increases the likelihood of encountering the problem: Schedule a simple activity with an event: Set the start time to the beginning of the current day and the end time to the end of the current day. Include an application token and a threshold (that you've already met for today 🙂). Once the activity is scheduled, monitor whether eventDidReachThreshold triggers in the device activity monitor extension. Workarounds I've discovered: Restart the activity: Not very reliable. Force restart the phone: A more drastic measure, but sometimes effective. Just wait: Wait for an undetermined amount of time, ranging from a few minutes to several hours, after which eventDidReachThreshold will start triggering just fine again. I've filed a bug report (FB13188666) concerning this specific issue. I'm curious to know if anyone else is experiencing it and what workarounds you've found!
3
1
738
Jan ’24
Detecting Termination and Re-establishing Connection with DeviceActivityReport App Extension
Hello, I have an iOS app using the DeviceActivityReport app extension. Occasionally, the extension gets terminated (likely due to reaching memory limit**), which in turn disrupts the connection with the main app. How can the main app detect when the DeviceActivityReport extension has been terminated due to memory constraints, and what's the best way to re-establish the connection afterward? Thanks in advance for your insights and suggestions! ** I'm also unsure why the extension should be reaching its memory limit. When profiling the extension in XCode, it never reaches above 15MB, and I know the limit is 100MB. It's not doing anything out of the ordinary - and I've seen very similar complaints about DeviceActivityReport terminating on these forums. Any thoughts on how to prevent termination in the first place would also be super helpful!
3
1
794
Sep ’23
Access The Duration Of Apps Usage Using Family Control API
I've successfully managed to present the duration using DeviceActivityReportExtension, however, I need to show the user how much time is left for him to use the monitored apps (The user answeres questions and gains screen time that he can then spend using Social apps). Everywhere I've looked said it is not possible to access the actual time duration spent on app but only to use DeviceActivityReportExtension to present it, but the app 1Question does exactly what I'm trying to achieve successfully.
1
0
371
Sep ’23
Device Activity Report Extension Crashed when adding 3 or more reports on one screen
Activity Report Extension crashes when adding 3 or more reports on one screen. I'm trying to use the new Screen Time API from WWDC 2021 and 2022 I'm trying to show 3 reports on one screen, I created a simple SwiftUI app to demonstrate the issue where just a Text for each report is displayed. They all appear for a few seconds and then disappear with an error in the debug console. Our project is stuck because having 1 device activity report for all elements results in poor performance. The whole API seems laggy, but I'm wondering if it's an issue on my side or Apple's bug. Screen Recording https://drive.google.com/file/d/1DniOo4QN5bY56sddZJvLTKtkGLQugXRi/view?usp=share_link I'm getting the following error in the Xcode debug console 2023-09-02 22:36:37.763861-0400 TestApp3[6222:368344] [default] VS terminated with error: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted} All targets and the project have Deployment Target iOS 16, I'm using XCode 14.3.1, and testing on iPhone 11 iOS 16.6 ContentView.swift struct ContentView: View { var body: some View { VStack { DeviceActivityReport(.init("Total Activity1")) Spacer(minLength: 16) DeviceActivityReport(.init("Total Activity2")) Spacer(minLength: 16) DeviceActivityReport(.init("Total Activity3")) } } } ActivityReport.swift @main struct ActivityReport: DeviceActivityReportExtension { var body: some DeviceActivityReportScene { TotalActivityReport1 { totalActivity in .init(totalActivity: totalActivity) } TotalActivityReport2 { totalActivity in .init(totalActivity: totalActivity) } TotalActivityReport3 { totalActivity in .init(totalActivity: totalActivity) } } } TotalActivityReport.swift extension DeviceActivityReport.Context { static let totalActivity1 = Self("Total Activity1") static let totalActivity2 = Self("Total Activity2") static let totalActivity3 = Self("Total Activity3") } struct TotalActivityReport1: DeviceActivityReportScene { let context: DeviceActivityReport.Context = .totalActivity1 let content: (String) -> TotalActivityView1 func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> String { "Test1" } } struct TotalActivityReport2: DeviceActivityReportScene { let context: DeviceActivityReport.Context = .totalActivity2 let content: (String) -> TotalActivityView2 func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> String { "Test2" } } struct TotalActivityReport3: DeviceActivityReportScene { let context: DeviceActivityReport.Context = .totalActivity3 let content: (String) -> TotalActivityView3 func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> String { "Test3" } } TotalActivityView.swift struct TotalActivityView1: View { let totalActivity: String var body: some View { Text(totalActivity) } } struct TotalActivityView2: View { let totalActivity: String var body: some View { Text(totalActivity) } } struct TotalActivityView3: View { let totalActivity: String var body: some View { Text(totalActivity) } }
0
1
501
Sep ’23
DeviceActivityMonitorExtension - intervalDidStart doesn't get called
Hello, I have an app that you can select apps and then start monitoring. When I restrict the apps by button click, and monitor the activity, the scheduled time works and intervalDidEnd cancels shielding apps. But when I schedule shielding apps, intervalDidStart doesn't start shielding. What am I missing here? I have already added FamilyControls capability. import SwiftUI @main struct TestingScreenTimeAPIApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } import SwiftUI struct ContentView: View { @StateObject var model = MyModel.shared @State var isPresented = false var body: some View { VStack { Button("Select Apps") { isPresented = true } .familyActivityPicker(isPresented: $isPresented, selection: $model.selectionToDiscourage) Button("Start monitoring") { model.startMonitoring() } .padding() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } import Foundation import FamilyControls import DeviceActivity class MyModel: ObservableObject { static let shared = MyModel() private init() {} var selection: FamilyActivitySelection? = nil var selectionToDiscourage = FamilyActivitySelection() { willSet { selection = newValue } } func startMonitoring() { let intervalStart = DateComponents(hour: 11, minute: 09) let intervalEnd = DateComponents(hour: 13, minute: 14) let schedule = DeviceActivitySchedule( intervalStart: intervalStart, intervalEnd: intervalEnd, repeats: true) let center = DeviceActivityCenter() do { try center.startMonitoring(.activity, during: schedule) } catch { print ("Error: \(error)") } } } extension DeviceActivityName { static let activity = Self("activity") } import UIKit import FamilyControls class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { Task { do { try await AuthorizationCenter.shared.requestAuthorization(for: .individual) } catch { print("Error: \(error.localizedDescription)") } } return true } } import DeviceActivity import FamilyControls import ManagedSettings class DeviceActivityMonitorExtension: DeviceActivityMonitor { let store = ManagedSettingsStore() override func intervalDidStart(for activity: DeviceActivityName) { super.intervalDidStart(for: activity) let model = MyModel.shared if model.selection != nil { let applications = model.selection!.applicationTokens store.shield.applications = applications.isEmpty ? nil : applications } } override func intervalDidEnd(for activity: DeviceActivityName) { super.intervalDidEnd(for: activity) store.shield.applications?.removeAll() } }
3
1
636
Jan ’24
Filter content without MDM profile?
Hello! I'm new to iOS development and am developing an app that blocks certain websites. At the moment, I'm thinking of using the Network Extension capability to do the job. From what I have read, in the production version of the app, you'd need to make use of MDM profiles since NE filtering only works on supervised devices. So, I'm here to ask the community if there are better options than using this method. As far as screen time api is concerned, I believe it requires the user to specify which websites they want blocked by themselves using the activity picker so that doesn't quite work for me since i want to allow the app to block groups of websites by itself based on the user's preference. Thanks!
4
1
769
Sep ’23
Managed Settings shield website using a list of urls
Hello! Rookie Swift developer here! I am trying to make an app that uses the Screen Time API to block a list of websites. Specifically, I want it to take a list of web domains in String format and restrict them instead of using the FamilyActivityPicker. So far, I have been unsuccessful. When using the FamilyActivityPicker, I have been able to restrict websites by modifying the shield instance variable of the ManagedSettingsStore. let store = ManagedSettingsStore() // Got selection from familyActivityPicker. store.shield.webDomains = selection.webDomainTokens "store.shield.webDomains" is of type "Set<Token>" and as far as I know, you can create a WebDomain struct with a String url but not Token. I was only able to get a token using the FamilyActivityPicker. Hence, I was wondering if it was even possible to do this and if so, how you'd go about it. Thanks!
1
1
563
Aug ’23
DeviceActivityMonitor not working on development since I've had my Family Controls (Distribution) entitlement approved
I recently got approved for the Family Controls (Distribution) entitlement, and since then it seems that I cannot use the DeviceActivityMonitor extension on the dev environment anymore. I've tried attaching a debugger to the DeviceActivityMonitor process but it's never called so does not attach, and I can't see why it is not attaching. I've tried reverted back to old versions which I know definitely worked, and it's still not working... However, the DeviceActivityReport extension seems to be working fine. Any help or advice on how I can actually debug this would be greatly appreciated!
1
0
512
Aug ’23
Irrecoverable Crash in Extension
We are seeing cases where DeviceActivityMonitoring extension is crashing permanently. This is due to a now-fixed bug that was causing a stack overflow. On devices where the extension crashed, it appears permanently unable to recover - even weeks after the crash and after multiple restarts of the device. It looks like recovery is being attempted, as the same four NSLog activities are emitted roughly every second that the phone is active. Logs: Process: DeviceActivityMonitoring Activity: beginning extension request Message: NSExtensionPrincipalClass `<private>` does not conform to NSExtensionRequestHandling protocol! Process: DeviceActivityMonitoring Activity: Loading Preferences From User Session CFPrefsD Message: Process: DeviceActivityMonitoring Activity: container_system_group_path_for_identifier Message: Requesting container lookup; class = 13, identifier = <private>, group_identifier = <private>, create = 1, temp = 0, euid = 501, uid = 501 container_query_get_single_result: success container_system_group_path_for_identifier: success Process: DeviceActivityMonitoring Activity: container_create_or_lookup_app_group_path_by_app_group_identifier Message: Requesting app group container lookup; personaid = 1000, type = DEFAULT, name = 9F7F4BA7-79CF-453C-B81C-568E96ADB711, origin [pid = 29, personaid = 199], proximate [pid = 3505, personaid = 199], identifier = <private>, euid = 501, uid = 501, platform = 2 containermanagerd stat [<private>]: exists: 1, isDirectory: 0, fsNode: <~~~> containermanagerd <private> is sandboxed. Issuing token for path: [<private>] (extension class: com.apple.sandbox.application-group) containermanagerd [0] command=38, client=<<~~~>, u=<501/501/~~/0/1000>, uid=501, pid=5595, sandboxed=1, platform=2 (1/1/0) [<~~~>], cached, cs cached>, error=(null) Consuming sandbox extension; path = [<private>], key = 0 Revoking sandbox extension; key = 0 Can anyone provide some insight into what is going on with the recovery attempt here? Practically, how can we recover the extension in these cases? Will an app update force the extension to restart properly? Hard reset of the device? Something else? Is there any way to check on the health of an extension from the main app so that we can deterministically know if the extension is healthy or not before relying on it?
1
1
538
Aug ’23
Target is null when adding an extension (Device Activity Monitor Extension)
When I try to add an extension to my Xcode project, I get the following warning: Activate “MyMonitor” scheme? This scheme has been created for the “(null)” target. Choose Activate to use this scheme for building and debugging. Schemes can be chosen in the toolbar or Product menu. I'm trying to understand a few things about this error: What exactly does the "(null)" target refer to? Could it be that Xcode is creating the scheme before the target is complete? Could this "(null)" target be the reason my code doesn't seem to be connecting properly to my app extension? How can I correct this issue? I ran into this during the process of trying to add a Device Activity Monitor Extension to my iOS project. Any hints are welcome, I have been stuck on this for too long.
6
1
1.2k
Oct ’23
Memory limit for Device Activity Monitor Extension
I am trying to develop an application that can enforce Screen Time restrictions on the target device, however I get stuck at the part where I have scheduled callbacks for my class that implements the extension for DeviceActivityMonitor. For debugging, I first attach to the app extension target process via Debug > Attach to Process > Process Name. But after scheduling monitoring that receives a callback immediately, the process exits with the following error: Thread 1: EXC_RESOURCE (RESOURCE_TYPE_MEMORY: high watermark memory limit exceeded) (limit=6 MB) Is the maximum allowed memory for Device Activity Monitor extensions really just 6 MB, or am I doing something wrong? If it is indeed the case, is there any way to increase it? 6 MB seems quite restrictive to me.
1
2
791
Aug ’23