How to properly use the completionHandler when performing a background fetch?

假如想象 提交于 2019-12-08 04:32:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!