问题
I'm having a hard time wrapping my head around using completionHandler
inside performFetchWithCompletionHandler
in the AppDelegate
.
My App does some background fetching, and during the fetch I would like to invoke a function that is located in one of my viewControllers
What is the correct way to use the completionHandler
, I'm aware that it is an asynchronous task.
I managed to make it work when I wanted to send data to my database, but I'm unable to make it work when I want to invoke a function located in one of the viewControllers
Attempt: What is the right way to call completionHandler
?
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if let tabBarController = window?.rootViewController as? UITabBarController,
viewControllers = tabBarController.viewControllers as [UIViewController]! {
for viewController in viewControllers {
if let myViewController = viewController as? MyViewController {
myViewController.myFunction()
print("background fetch done")
completionHandler(.NewData)
print("background fetch done")
}
}
}
}
P.S: Here is the attempt that was successful, this is when I was sending data to my database:
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let name = UIDevice.currentDevice().name
let val = "\(name): \(timeFormatter.stringFromDate(NSDate()))"
db.childByAutoId().setValue(val) { _ in
print("Background Fetch Completed")
completionHandler(.NewData)
}
}
来源:https://stackoverflow.com/questions/38258399/how-to-properly-use-the-completionhandler-when-performing-a-background-fetch