5

我按照所有步骤进行了设置,background fetch但我怀疑我performFetchWithCompletionHandler在 AppDelegate 中编写函数时犯了一个错误。

这是我模拟后立即收到的警告background fetch

Warning: Application delegate received call to -  application:
performFetchWithCompletionHandler:but the completion handler was never called.

这是我的代码:

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 notificationViewController = viewController as? NotificationsViewController {
         firstViewController.reloadData()
         completionHandler(.NewData)
         print("background fetch done")
      }
    }
  }
}

如何测试是否background-fetch正常工作?

4

1 回答 1

3

如果您不输入第一个 if 语句,则永远不会调用完成处理程序。此外,当您遍历视图控制器时,您可能找不到您正在寻找的视图控制器,这意味着永远不会调用完成。最后,您可能应该return在调用完成处理程序之后放置一个。

func application(
    application: UIApplication,
    performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    guard let tabBarController = window?.rootViewController as? UITabBarController,
        let viewControllers = tabBarController.viewControllers else {
        completionHandler(.failed)
        return
    }

    guard let notificationsViewController = viewControllers.first(where: { $0 is NotificationsViewController }) as? NotificationsViewController else {
        completionHandler(.failed)
        return
    }

    notificationViewController.reloadData()
    completionHandler(.newData)
}
于 2016-02-25T23:59:54.343 回答