您好,我已经在plist.info中配置了后台任务,并将其标识符为"updateCountry",并将后台模式作为获取和处理功能. 我有具有此功能的LocationManager...

    func registerBackgroundTask() {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "updateCountry", using: nil) { task in
        self.handleAppRefresh(task: task as! BGAppRefreshTask)
        print("register backgoundtask")
    }
}

func handleAppRefresh(task: BGAppRefreshTask) {
    print("registrando pais")
    scheduleBackgroundTask()
    DispatchQueue.global().async {
        self.detectCountry()
      
        task.setTaskCompleted(success: true)
        print("Background task completed.")
    }
}

func scheduleBackgroundTask() {
    print("request updateCountry")
    let request = BGAppRefreshTaskRequest(identifier: "updateCountry")
    request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 1) // 1 minute

    do {
        try BGTaskScheduler.shared.submit(request)
        print("Background task scheduled successfully.")
    } catch {
        print("Unable to submit task: \(error)")
    }
}

我以这种方式调用这些函数,其中,AppAppRefresh调用一个类函数来检测您所在的国家并添加到数组中.一切似乎都很好,我没有错误,但没有什么是在控制台打印,不工作或更新国家列表.

    var body: some Scene {
    WindowGroup {
        ContentView()
        
    }
    .modelContainer(container)
    .backgroundTask(.appRefresh("updateCountry")) {
        await locationManager.registerBackgroundTask()
    }
    
  
}

有谁知道如何解决这个问题,或者问题出在哪里?谢谢!

推荐答案

.backgroundTask(.appRefresh("updateCountry"))

是的SwiftUI版本

 BGTaskScheduler.shared.register

将您的代码更改为类似

.backgroundTask(.appRefresh("updateCountry")) {
    //The task you want performed.
    scheduleBackgroundTask() //Must be sync or async/await, don't use GCD
    detectCountry() //Must be sink or async/await, don't use GCD

}

别忘了第一次在别的地方打scheduleBackgroundTask().

在开发模式下,您可以通过在submit后放置断点来按需触发后台任务

do {
    try BGTaskScheduler.shared.submit(request)
    print("Background task scheduled successfully.")

    //ADD breakpoint here
} catch {
    print("Unable to submit task: \(error)")
}

然后,当您运行应用程序时,断点被触发,请在调试器中键入.

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

在你的 case 中,TASK_IDENTIFIER是"更新国家/地区".

https://developer.apple.com/documentation/backgroundtasks/starting_and_terminating_tasks_during_development

但有一件事需要注意.后台任务不会每分钟都运行.你可以这样建议,但苹果将决定何时运行,不要期待任何事情超过每小时一次.

对于像位置这样的东西,你最好使用LocationManager.

https://developer.apple.com/documentation/corelocation/handling_location_updates_in_the_background#

既然你监控的是"国家","位置的重大改变"可能是正确的解决方案.

https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati

Swift相关问答推荐

如何更新Square Order?

格式化单位和度量值.为什么从符号初始化的单位不能产生与静态初始化相同的结果

如何在自定义视图中读取修改符子元素?

是否可以循环遍历SWIFT子类并访问它们的静态变量S?

如何使用变量 Select 哪个向量(?)在我的 struct 中密谋吗?

正在接收具有不完整数据错误的URL请求

当将新值推送到 NavigationStack 时,SwiftUI 的 navigationDestination 已在堆栈的早期声明

使用变量(而非固定)的字符串分量进行Swift正则表达式

应该在ViewModel还是ViewController中使用"Task {}"?

暂停我的 AR 会话并清除变量和锚点的功能

使用异步收集发布者值

如何为等待函数调用添加超时

如何自己实现同一个 iOS 16 锁屏圆形小部件?

格式化大货币数字

为什么 SwiftUI 不在工具栏菜单中反映 @State 属性值?

在 RealityKit 中创建转场

Vapor Swift 如何配置客户端连接超时

Swift 5.0 编译器无法导入使用 Swift 4.2.1 编译的模块

如何在 SwiftUI 中打开 ImagePicker?

如何将应用程序与 iOS 联系人应用程序集成?