BackgroundTasks 中的 BGAppRefreshTask

Ada*_*lma 12 iphone xcode ios swift

我有这段代码,当应用程序处于后台时,它会显示一条消息“Msg Background”。我需要的是,只要应用程序继续在后台显示该消息每 2 分钟(只是一个时间示例)。到目前为止,我的代码只显示了一次消息,显然这句话不能正常工作。

UIApplication.shared.setMinimumBackgroundFetchInterval (UIApplication.backgroundFetchIntervalMinimum)
Run Code Online (Sandbox Code Playgroud)

我也有这个警告:'setMinimumBackgroundFetchInterval' 在 iOS 13.0 中被弃用:在 BackgroundTasks 框架中使用 BGAppRefreshTask 代替

我正在使用 swift 5 和 Xcode 11

class AppDelegate: UIResponder, UIApplicationDelegate {



func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    GMSServices.provideAPIKey("AIzaSyBSpAt5zqvbh73FmG_Kb6xpiFMkWRmHppg")
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
    return true
}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("Msg Background")
}

}
Run Code Online (Sandbox Code Playgroud)

小智 5

正如 Paulw11 所说,它不是在固定时间间隔内调用的。操作系统控制它何时执行。我们不能因此而期望具体的时间。

您可能知道这一点,但我将添加这一点以防万一,setMinimumBackgroundFetchInterval已在 iOS 13 及更高版本上弃用。您可能要考虑改用BackgroundTasks 框架

但是如果你想测试 performFetchWithCompletionHandler,你可以使用 XCode Navigation Bar > Debug > perform Background Fetch。

用于查找选项的 XCode 导航栏屏幕截图

我希望它能有所帮助!