Background Modes - toant-dev/toandev.github.io GitHub Wiki
func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.endBackgroundTask()
}
assert(backgroundTask != .invalid)
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
Setting Up a Background Fetch
In order to implement background fetch, there are three things you must do:
Check the box Background fetch in the Background Modes of your app’s Capabilities. Use setMinimumBackgroundFetchInterval(:) to set a time interval appropriate for your app. Implement application(:performFetchWithCompletionHandler:) in your app delegate to handle the background fetch.
UIApplication.shared.setMinimumBackgroundFetchInterval(
UIApplication.backgroundFetchIntervalMinimum)
// Support for background fetch
func application(
_ application: UIApplication,
performFetchWithCompletionHandler
completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//1
if let tabBarController = window?.rootViewController as? UITabBarController,
let viewControllers = tabBarController.viewControllers {
//2
for viewController in viewControllers {
if let fetchViewController = viewController as? FetchViewController {
//3
fetchViewController.fetch {
//4
fetchViewController.updateUI()
completionHandler(.newData)
}
}
}
}
}