How to run Timer into the ShieldActionExtension to wait user for 5 second to unlock the app?

// Make sure that your class name matches the NSExtensionPrincipalClass in your Info.plist. class ShieldActionExtension: ShieldActionDelegate {   override func handle(action: ShieldAction, for application: ApplicationToken, completionHandler: @escaping (ShieldActionResponse) -> Void) {     // Handle the action as needed.     switch action {       case .primaryButtonPressed:         completionHandler(.defer)       case .secondaryButtonPressed:         Timer(timeInterval: 5, repeats: false) { timer in           Restrictions.shared.unlockedAllApps()         }                   completionHandler(.defer)       @unknown default:         fatalError()     }   }           override func handle(action: ShieldAction, for webDomain: WebDomainToken, completionHandler: @escaping (ShieldActionResponse) -> Void) {     // Handle the action as needed.     print("func handle(action: ShieldAction, for webDomain: WebDomainToken,")     completionHandler(.close)   }       override func handle(action: ShieldAction, for category: ActivityCategoryToken, completionHandler: @escaping (ShieldActionResponse) -> Void) {     // Handle the action as needed.     NSLog("handle(action: ShieldAction, for category: ActivityCategoryToken")     completionHandler(.defer)   } }

Answered by Frameworks Engineer in 744641022

ShieldActionExtensions will exit shortly after the completionHandler is called, so the Timer's closure will likely not be run before your extension's lifecycle ends. A better option would be to use a DeviceActivityMonitor extension. When the secondary button gets pressed, your ShieldActionExtension can create a DeviceActivitySchedule that starts 5 seconds from Date.now and start monitoring that schedule using a DeviceActivityCenter. Your DeviceActivityMonitor extension can then call Restrictions.shared.unlockAllApps() when it receives the intervalDidStart callback for that schedule.

Accepted Answer

ShieldActionExtensions will exit shortly after the completionHandler is called, so the Timer's closure will likely not be run before your extension's lifecycle ends. A better option would be to use a DeviceActivityMonitor extension. When the secondary button gets pressed, your ShieldActionExtension can create a DeviceActivitySchedule that starts 5 seconds from Date.now and start monitoring that schedule using a DeviceActivityCenter. Your DeviceActivityMonitor extension can then call Restrictions.shared.unlockAllApps() when it receives the intervalDidStart callback for that schedule.

Thanks for ther reply but i got the solution we can achieve it by using DispacthQueue.main.asyncAfer.

How to run Timer into the ShieldActionExtension to wait user for 5 second to unlock the app?
 
 
Q