my swift app needs to run a piece of code periodically even while being in the background. What is the best way to accomplish that?
i tried DispatchQueue.global(qos: .background).async
but that didnt work
new try:
i added this to my ViewController:
private var time: Date?
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .long
return formatter
}()
func fetch(_ completion: () -> Void) {
time = Date()
completion()
}
and this to my AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
// Override point for customization after application launch.
return true
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let tabBarController = window?.rootViewController as? UITabBarController,
let viewControllers = tabBarController.viewControllers
{
for viewController in viewControllers {
if let fetchViewController = viewController as? ViewController {
fetchViewController.fetch {
completionHandler(.newData)
print("fired")
}
}
}
}
}
and put a breakpoint on completionHandler(.newData)
.
But when i run the app, the breakpoint never gets triggered. and the print statement never executed.