ios - 使用 BGTaskScheduler 进行后台获取可以完美地与调试模拟配合使用,但在实践中却无法使用

标签 ios swift xcode background

我在appDelegate的didFinishLaunchingWithOptions中注册了后台抓取任务:

BGTaskScheduler.shared.register(forTaskWithIdentifier: BackgroundScheduler.shared.backgroundTaskId, using: DispatchQueue.main) { task in

    BackgroundScheduler.shared.handleAppRefresh(task: task as! BGAppRefreshTask)
}

handleAppRefersh 函数调度另一个刷新任务并调用该操作的 fetch 方法,并在完成 fetch 操作后传递一个完成处理程序以运行。

func handleAppRefresh(task: BGAppRefreshTask) {
    
    os_log("handleAppRefresh exetued.")
    
    scheduleAppRefresh()
    
    task.expirationHandler = {
        os_log("backgroundFetch expiration called")
    }
    
    operation.fetch() {
        os_log("backgroundFetch fetch called")
        task.setTaskCompleted(success: true)
    }
}

scheduleAppRefresh 提交 BGAppRefreshTAskRequest 以重复后台获取执行。

func scheduleAppRefresh() {
    
    os_log("scheduleAppRefresh exetued.")
    
    let request = BGAppRefreshTaskRequest(identifier: backgroundFetchId)
    request.earliestBeginDate = Date(timeIntervalSinceNow: AppSettings.refreshInterval)

    do {
        try BGTaskScheduler.shared.submit(request)
    } catch {
        os_log("Could not schedule app refresh:", error.localizedDescription)
    }
}

refreshInterval 为 10 * 60,即 10 分钟。

operation.fetch 方法检查设备的当前位置并向远程服务器发送请求。最后它发送本地通知,更新 UI 并调用以下代码:

task.setTaskCompleted(success: true)

在 Xcode 中检查了“位置更新”和“后台获取”功能,并将所需设置添加到 info.plist。

当我使用以下调试命令测试后台获取功能时,一切正常,调试器中没有任何警告消息。

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"TASK_IDENTIFIER"]

但是当我长时间将应用程序留在后台时,iOS 永远不会调用 handleAppRefresh 函数。

Xcode:12.2,iOS:14.2

项目公共(public) repo : https://github.com/amirrezaeghtedari/CoronaVirousRegulations.git

我完全糊涂了。

最佳答案

我已将后台获取间隔设置为 10 分钟,等待大约 4 小时或更长时间后,iOS 在后台运行我的应用程序。之后,我的应用程序在后台不定期地被调用,间隔时间从不到一小时到几个小时不等。很明显,我的实现没有问题,这些执行间隔取决于 iOS 策略。

关于ios - 使用 BGTaskScheduler 进行后台获取可以完美地与调试模拟配合使用,但在实践中却无法使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64844812/

相关文章:

xcode - 如何获取 xcode 应用程序的 .app 文件

ios - 带有图像的自定义后退按钮

swift - 如何对在 Swift 中调用的私有(private)方法进行单元测试

iphone - 应用在iPhone 4上崩溃了吗?

c++ - 更改xcode中特定代码字的颜色

arrays - 在设备上本地保存自定义类数组

iphone - 如何在 iOS 设备上创建新的 EKCalendar?

html - 背景 :cover not scaling on mobile browsers

ios - 我在一个页面上显示所有用户的图片和教育,如何从列表中删除当前用户?

ios - pickerView 无法加载在同一 View Controller 中获取的数据(swift)