Screen Time

RSS for tag

Share and manage web-usage data, and observe changes made to Screen Time settings by a parent or guardian.

Posts under Screen Time tag

158 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

DeviceActivityReport - filtering applications for makeConfiguration
I am trying to filter my DeviceActivityReport to only show activity for the specific app tokens I pass in. Right now, it shows activity for all apps. Is there something else I need to do in makeConfiguration so that it only filters the application tokens that I'm filtering by? filter = DeviceActivityFilter(segment: .hourly(during: dateInterval), applications: task.selection.applicationTokens) struct TotalActivityReport: DeviceActivityReportScene { // Define which context your scene will represent. let context: DeviceActivityReport.Context = .totalActivity // Define the custom configuration and the resulting view for this report. let content: (String) -> TotalActivityView func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> String { // Reformat the data into a configuration that can be used to create // the report's view. let formatter = DateComponentsFormatter() formatter.allowedUnits = [.minute, .second] formatter.unitsStyle = .abbreviated formatter.zeroFormattingBehavior = .dropAll let totalActivityDuration = await data.flatMap { $0.activitySegments }.reduce(0, { $0 + $1.totalActivityDuration }) return formatter.string(from: totalActivityDuration) ?? "No activity data" } }
1
0
701
Aug ’23
Family Controls crash when app launching
Hey 👋 I have an app that uses Device Activity Monitor. For the previous releases there was no problem. However I made some improvements in my app and send it to review. Review team getting following crash log but I couldn't find the issue. It's working both in my simulator and a real devices.(iPhone, iPad). I removed some logs from here because of character limitations. Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 2343432205 <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-create watchdog transgression: application<>:15592 exhausted real (wall clock) time allowance of 19.97 seconds ProcessVisibility: Foreground ProcessState: Running WatchdogEvent: scene-create WatchdogVisibility: Foreground WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 7.760 (user 4.070, system 3.690), 5% CPU", "Elapsed application CPU time (seconds): 0.111, 0% CPU" ) reportType:CrashLog maxTerminationResistance:Interactive> Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1d8256ca4 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1d8269b74 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x1d8269e4c mach_msg_overwrite + 540 3 libsystem_kernel.dylib 0x1d82571e8 mach_msg + 24 4 libdispatch.dylib 0x1a108320c _dispatch_mach_send_and_wait_for_reply + 548 5 libdispatch.dylib 0x1a108359c dispatch_mach_send_with_result_and_wait_for_reply + 60 6 libxpc.dylib 0x1f8fa9218 xpc_connection_send_message_with_reply_sync + 240 7 Foundation 0x193f6ff18 __NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__ + 16 8 Foundation 0x193f032c4 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 2192 9 Foundation 0x193f01ac0 -[NSXPCConnection _sendSelector:withProxy:arg1:] + 116 10 Foundation 0x193f019f8 _NSXPCDistantObjectSimpleMessageSend1 + 60 11 FamilyControls 0x1e772388c 0x1e76ee000 + 219276 12 FamilyControls 0x1e7722b0c 0x1e76ee000 + 215820 13 libdispatch.dylib 0x1a1067eac _dispatch_client_callout + 20 14 libdispatch.dylib 0x1a10696ec _dispatch_once_callout + 32 15 FamilyControls 0x1e7722d18 0x1e76ee000 + 216344 16 MyApp 0x102314bfc AppUsagesViewModel.init(dependencies:) + 510972 (AppUsagesViewModel.swift:29) 17 MyApp 0x1022b2b00 closure #1 in MainTabBarController.setupTabbar() + 109312 (MainTabBarController.swift:55) 18 MyApp 0x1022b3904 specialized Sequence.compactMap<A>(_:) + 112900 (<compiler-generated>:0) 19 MyApp 0x1022b2750 MainTabBarController.setupTabbar() + 108368 (MainTabBarController.swift:47) 20 MyApp 0x1022b29a8 @objc MainTabBarController.viewDidLoad() + 108968 (<compiler-generated>:0) 21 UIKitCore 0x19bf381f4 -[UITabBarController initWithNibName:bundle:] + 156 22 MyApp 0x1022b3a7c specialized static MainTabBarController.build(_:) + 113276 (MainTabBarController.swift:96) 23 MyApp 0x102313f80 specialized AppDelegate.application(_:didFinishLaunchingWithOptions:) + 507776 (AppDelegate.swift:45) 24 MyApp 0x1023132d8 @objc AppDelegate.application(_:didFinishLaunchingWithOptions:) + 504536 (<compiler-generated>:17) As far as I understood from the log the crash is happened right there AppUsagesViewModel.swift:29. I have a following variable in that line. private let parentalControls = AuthorizationCenter.shared What could be the reason of that crash? If someone can help me I really appreciate it. Thanks!
4
0
646
Aug ’23
Screentime api DeviceActivityEvent is not firing.
I've setup screen time api with encouraged & discouraged apps and monitoring apps. var selectionToDiscourage = FamilyActivitySelection() { willSet { print ("got here \(newValue)") let applications = newValue.applicationTokens let categories = newValue.categoryTokens //let webCategories = newValue.webDomainTokens store.shield.applications = applications.isEmpty ? nil : applications store.shield.applicationCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set()) store.shield.webDomainCategories = ShieldSettings.ActivityCategoryPolicy.specific(categories, except: Set()) } } let events: [DeviceActivityEvent.Name: DeviceActivityEvent] = [ .encouraged: DeviceActivityEvent( applications: selectionToDiscourage.applicationTokens, threshold: DateComponents(minute: 10)) ] print ("Could not start monitoring \(selectionToDiscourage)") let center = DeviceActivityCenter() center.stopMonitoring() do { try center.startMonitoring(.daily, during: schedule, events: events) } catch { print ("Could not start monitoring \(error)") } extension DeviceActivityName { static let daily = Self("daily") } @available(iOS 15.0, *) extension DeviceActivityEvent.Name { static let encouraged = Self("encouraged") } ideally once the encouraged apps reaches 10mins screentime I should have received an event in DeviceActivityMonitorExtension. However i am not receiving any event here. super.eventDidReachThreshold(event, activity: activity) print("eventDidReachThreshold", event) store.shield.applications = nil store.shield.applicationCategories = nil // Handle the event reaching its threshold. } Please help.
2
0
440
Aug ’23
Block a category using ManagedSettings
I'm trying to block the entire "social" category using ManagedSettings. However, the function blockApps does not work because of a compiler error on the let socialCategory = AcitivityCategoryToken line ("(Argument type '(UnboundedRange_) -> ()' does not conform to expected type 'Decoder')" and "Missing argument label 'from:' in call"). The code is the exact same as the WWDC 2022 (this video) but it still does not work. import ManagedSettings extension ManagedSettingsStore.Name { static let social = Self("social") } public class ScreenTimeApiModule: Module { public func definition() -> ModuleDefinition { Name("ScreenTimeApi") Function("blockApps") { let socialCategory = ActivityCategoryToken(...) //ERROR "(Argument type '(UnboundedRange_) -> ()' does not conform to expected type 'Decoder')" and "Missing argument label 'from:' in call" let socialStore = ManagedSettingsStore(named: .social) socialStore.shield.applicationCategories = .specific([socialCategory]) print("Successfully blocked apps") } } }
1
0
423
Aug ’23
Schedule Task (Screen Time API) on iOS in background mode
I have developed a Flutter application to lock selected apps using the Screen Time API (iOS). My app has been registered in Family Control and currently successfully executes app restrictions in both emulators and devices through TestFlight. I intend to incorporate a countdown timer feature to ensure that the app restriction function is activated when the timer stops (e.g 15 minutes after function called). However, the issue I'm facing is that on iOS, when the app goes into the background mode, all processes, including the countdown, halt, rendering the restriction function unusable. I have attempted various mechanisms, such as: DeviceActivityMonitor extension => Not triggered even though DeviceActivitySchedule is set. Cron => Stops when in background mode. Local notification => Only triggered when the user interacts with the notification, not automatically execute function in background Is there a solution to address this matter? Here is my snippet code, startAppRestrictions() is already work, but I need to started it after 15 minutes (I tried on schedulingRestrictions() function) import Foundation import FamilyControls import ManagedSettings import DeviceActivity private let _MyModel = MyModel() class MyModel: ObservableObject { let store = ManagedSettingsStore() @Published var familyActivitySelection: FamilyActivitySelection var selectAppTitle: String = "" var cancelButtonTitle: String = "" var doneButtonTitle: String = "" init() { familyActivitySelection = FamilyActivitySelection() } class var shared: MyModel { return _MyModel } func startAppRestrictions() { print("setShieldRestrictions") // Pull the selection out of the app's model and configure the application shield restriction accordingly let applications = MyModel.shared.familyActivitySelection if applications.applicationTokens.isEmpty { print("empty applicationTokens") } if applications.categoryTokens.isEmpty { print("empty categoryTokens") } //lock application store.shield.applications = applications.applicationTokens.isEmpty ? nil : applications.applicationTokens store.shield.applicationCategories = applications.categoryTokens.isEmpty ? nil : ShieldSettings.ActivityCategoryPolicy.specific(applications.categoryTokens) //more rules store.media.denyExplicitContent = true //prevent app removal store.application.denyAppRemoval = true print("deny app removal: ", store.application.denyAppRemoval ?? false) //prevent set date time store.dateAndTime.requireAutomaticDateAndTime = true } func stopAppRestrictions(){ //lock application store.shield.applications = nil store.shield.applicationCategories = nil //more rules store.media.denyExplicitContent = false //prevent app removal store.application.denyAppRemoval = false print("deny app removal: ", store.application.denyAppRemoval ?? false) //prevent set date time store.dateAndTime.requireAutomaticDateAndTime = false } func isAppLocked() -> Bool { let isShieldEmpty = (store.shield.applicationCategories == nil); return !isShieldEmpty } func countSelectedAppCategory() -> Int { let applications = MyModel.shared.familyActivitySelection return applications.categoryTokens.count } func countSelectedApp() -> Int { let applications = MyModel.shared.familyActivitySelection return applications.applicationTokens.count } func schedulingRestrictions() { print("Start monitor restriction") // Schedule restriction 15 minutes after started let now = Date() let fiveMinutesLater = Calendar.current.date(byAdding: .minute, value: 15, to: now) let schedule = DeviceActivitySchedule(intervalStart: Calendar.current.dateComponents([.hour, .minute], from: now), intervalEnd: Calendar.current.dateComponents([.hour, .minute], from: fiveMinutesLater ?? now), repeats: true, warningTime: nil) let center = DeviceActivityCenter() do { try center.startMonitoring(.restrictAppActivityName, during: schedule) print("Success with Starting Monitor Activity") } catch { print("Error with Starting Monitor Activity: \(error.localizedDescription)") } // Setting various properties of the ManagedSettingsStore instance let applications = MyModel.shared.familyActivitySelection if applications.applicationTokens.isEmpty { print("empty applicationTokens") } if applications.categoryTokens.isEmpty { print("empty categoryTokens") } print("monitoring model started") } } extension DeviceActivityName { static let restrictAppActivityName = Self("restrictApp") } My DeviceActivityMonitor extension import UIKit import MobileCoreServices import ManagedSettings import DeviceActivity class MyMonitor: DeviceActivityMonitor { override init() { print("device activity monitor inited") } override func intervalDidStart(for activity: DeviceActivityName) { super.intervalDidStart(for: activity) print("device activity monitor start") let model = MyModel.shared model.stopAppRestrictions() print("monitor started") } override func intervalDidEnd(for activity: DeviceActivityName) { super.intervalDidEnd(for: activity) print("device activity monitor end") let model = MyModel.shared model.startAppRestrictions() print("monitor stopped") } }
1
0
950
Aug ’23
ShieldConfigurationExtension - Color assets don't change with system Appearance
I've added ShieldConfigurationExtension to my project. The only thing that doesn't work for me is proper color for System Appearance. Let's say I only wants to change color of title for shield, I create color in Asset Catalog with different light and dark appearance then create ShieldConfiguration as shown: ShieldConfiguration(title: ShieldConfiguration.Label( text: "My title", color: UIColor(named: "mycolor") ?? .systemGray )) This will make the title to be one of the variant of mycolor BUT it looks to be randomly selected. Sometimes it has light appearance, sometimes dark and not always match selected system appearance. Other UI elements that I didn't set are properly changing theirs colors. On the other hand if I use some system colors, it works as expected: ShieldConfiguration(title: ShieldConfiguration.Label( text: "My title", color: .label )) .label will always has proper color - white for dark mode and black for light I've tried to use mycolor inside main app and there it works as it should so the problem is happening only in ShieldConfigurationExtension
0
1
549
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
582
Aug ’23
Family Controls Request Form
I've heard family controls request forms can take up to weeks and even months... I'm currently developing an app that requires the main target and also the app extension to both use Family Controls. Does this mean I need to request forms for both app bundles separately or just the main app? If I have to wait weeks or even months for both then that's a bit painful tbh. Is there a way to distribute to testflight without getting approved for the family controls entitlement? Thanks
5
0
924
Apr ’24
SHIELD an App for a certain Time
i write a function to shield the apps and another that unshield them func startAppRestrictions() { print("setShieldRestrictions") // Lock all application categories store.shield.applicationCategories = .all() store.shield.webDomainCategories = .all() // Prevent app removal store.application.denyAppRemoval = true print("deny app removal: ", store.application.denyAppRemoval ?? false) // Prevent set date time store.dateAndTime.requireAutomaticDateAndTime = true } func endAppRestrictions(){ //some code } i want that the shield works only for a certain time. The idea was to set a timer and call the first function and after a certain time call the other one. There is a better way to do so.
0
0
334
Aug ’23
How to get FamilyActivitySelection from DeviceActivityMonitorExtension in iOS Screen Time API
I have developed an application to lock selected apps using the Screen Time API (iOS). My app has been registered in Family Control and currently successfully executes app restrictions in both emulators and devices through TestFlight. I intend to incorporate a countdown timer feature to ensure that the app restriction function is activated when the timer stops. However, the issue I'm facing is I can't get FamilyActivitySelection values from DeviceActivityMonitorExtension, and it causes the selected app always empty and I can't do restrictions. I have attempted various ways, such as: Using singleton on MyModel Using the same App Groups for both App & Extension Target Using UserDefault to save & load FamilyActivitySelection values (already tested on App and it returns the correct value, but when I call it from DeviceActivityMonitorExtension and show it with local notification, the value is always empty) Is there any solution to address this matter? I put my code in here https://stackoverflow.com/questions/76935721/how-to-get-familyactivityselection-from-deviceactivitymonitorextension-in-ios-sc
0
0
469
Aug ’23
Unable to get app wise usage duration using Screen time API
I am working with DeviceActivity to get the screen time. I always have screen time zero second (0s). But it should have some value. I am selecting apps using familyActivityPicker and passing the tokens in the filter. @State private var context: DeviceActivityReport.Context = .init(rawValue: "Total Activity") filter = DeviceActivityFilter( segment: .daily( during: Calendar.current.dateInterval( of: .weekOfYear, for: .now )! ), users: .all, devices: .init([.iPhone, .iPad]), applications: applications, categories: categories, webDomains: webDomains ) DeviceActivityReport(context, filter: filter) I saw various posts regarding this, but nothing working in my side. I am unable to identify the issue of getting zero second all the time.
1
0
485
Aug ’23
IPhone 14 Battery Health Declining Faster than Expected
I got this iPhone 14 in Product Red, 128 GB in February 2023, the same year I'm posting this. I've mainly used it for taking photos and calling my partner, with less than 8 apps and around 1,000 photos stored. I always use the original cable for charging and don't play games in the phone (TBH, I don't have any games in this phone) that could harm the battery. However, the battery health has dropped to 93%, which is lower than expected for just 6 months of use. While some may argue that this figure is still quite acceptable, it falls short of what I anticipated for a new device with only six months of usage. I can draw a comparison with my previous phone, my previous phone, an iPhone SE 2021, endured heavy gaming for 12 hours a day and didn't have such a battery drop in the same timeframe. I'm genuinely curious if there's an issue with this new phone, even though I follow charging best practices by not going above 80% or below 20%.
1
0
793
Aug ’23
Screen Time Picker
Hello, I'm working with Screen Time API and I have such issue. When opening the picker with apps that I want to block, and doing a "Search" I don't have the Done CTA or Cancel. It dissapears and there are no way to get out by using button, except clicking on empty space. We see that other apps managed to add Cancel button. Could you please let us know how to do the same changes to our picker?
0
0
334
Aug ’23
Screen Time/ Schedules/ 15 minutes limitation
Hello, I'm working on the Parental Control app and noticed that we have limitations for schedules. We need to create a schedule so that all apps are blocked for some time. We see that nothing happens, when we set up it for less than 15 minutes. Apps are not blocked. Also, we see the same limitation if we enable the schedule from 23:45 to 00:00. Could you tell if it is a limitation from Screen Time API or we can fix it?
0
0
355
Aug ’23
Stability issues with ManagedSettings on iOS 16.6? Lots of new crashes
Hello, I am curious if someone else also noticed this. We have started getting reports about our app not working correctly (mostly related to the Device Activity monitor that "runs" in the background, https://developer.apple.com/documentation/deviceactivity/deviceactivitymonitor). Upon checking the Xcode Organizer I can see somewhat significant amount of crashes that mostly appear to happen on iOS 16.6 - it is possible that our users don't wait with updating iOS but still looks suspicious. The crashes are related to ManagedSettings calls outside our own code. We haven't changes this code in a while so this coupled with the fact that these crashes happen "deep" in the ManagedSettings framework leads me to believe there is some other issue.
3
0
779
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
722
Jan ’24
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
576
Sep ’23