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()
}
}