背景任务(.backgroundTask)不适用于 swiftui

问题描述 投票:0回答:1

您好,我已经在 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)")
    }
}

我以这种方式调用此函数,其中handleAppRefresh调用类函数来检测您所在的国家/地区并添加到数组中...一切看起来都很好,我没有错误,但控制台中没有打印任何内容,并且没有工作或更新国家列表...

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

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

swift swiftui background-task background-fetch bgtaskscheduler
1个回答
0
投票
.backgroundTask(.appRefresh("updateCountry"))

的 SwiftUI 版本
 BGTaskScheduler.shared.register

将您的代码更改为类似的内容

.backgroundTask(.appRefresh("updateCountry")) {
    scheduleBackgroundTask() //Must be sync or async/await
    detectCountry() //Must be sink or async/await

}

并且不要忘记第一次致电其他地方的

scheduleBackgroundTask()

© www.soinside.com 2019 - 2024. All rights reserved.