So I have been working with the screen time api. however I still cant get it to work to reshield certain apps after a certain time because for example Dispatch Queue just gets terminated after a certain time.
This is my code right now but the reshielding doesn't get called. Please help I have been working on this since weeks and weeks.
import ManagedSettings
import DeviceActivity
import Foundation
class ShieldActionExtension: ShieldActionDelegate {
let store = ManagedSettingsStore()
let center = DeviceActivityCenter()
override func handle(action: ShieldAction, for application: ApplicationToken, completionHandler: @escaping (ShieldActionResponse) -> Void) {
switch action {
case .primaryButtonPressed:
// Unshield the app
store.shield.applications?.remove(application)
// Encode and persist ApplicationToken
if let encoded = try? PropertyListEncoder().encode([application]) {
UserDefaults(suiteName: "group.Organization.BrainRipe.cmonnow")?.set(encoded, forKey: "StoredApplicationTokens")
}
let unshieldDurationMinutes = 2
let now = Date()
guard let endDate = Calendar.current.date(byAdding: .minute, value: unshieldDurationMinutes, to: now) else {
completionHandler(.close)
return
}
let activityName = DeviceActivityName("com.myapp.shield.reapply")
let schedule = DeviceActivitySchedule(
intervalStart: Calendar.current.dateComponents([.hour, .minute], from: now),
intervalEnd: Calendar.current.dateComponents([.hour, .minute], from: endDate),
repeats: false
)
do {
try center.startMonitoring(activityName, during: schedule)
} catch {
print("Error starting monitoring: \(error)")
}
completionHandler(.close)
case .secondaryButtonPressed:
completionHandler(.defer)
@unknown default:
fatalError("Unhandled ShieldAction case.")
}
}
}
import DeviceActivity
import ManagedSettings
import Foundation
// Optionally override any of the functions below.
// Make sure that your class name matches the NSExtensionPrincipalClass in your Info.plist.
class DeviceActivityMonitorExtension: DeviceActivityMonitor {
let store = ManagedSettingsStore()
override func intervalDidStart(for activity: DeviceActivityName) {
super.intervalDidStart(for: activity)
// Handle the start of the interval.
}
override func intervalDidEnd(for activity: DeviceActivityName) {
guard let data = UserDefaults(suiteName: "group.Organization.BrainRipe.cmonnow")?.data(forKey: "StoredApplicationTokens"),
let tokens = try? PropertyListDecoder().decode([ApplicationToken].self, from: data) else {
return
}
let tokenSet = Set(tokens)
if store.shield.applications == nil {
store.shield.applications = tokenSet
} else {
store.shield.applications?.formUnion(tokenSet)
}
// Clear tokens after use
UserDefaults(suiteName: "group.Organization.BrainRipe.cmonnow")?.removeObject(forKey: "StoredApplicationTokens")
}
}