我试图在我的应用程序中使用BGProcessingTask,当我进行测试时,我的代码只执行一次,但我的任务是像wwdc2019展览中的示例那样运行它。我需要在用户关闭应用程序后,每15分钟这段代码工作并将数据发送到服务器,我做错了什么?
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.transistorsoft.process", using: nil) { (task) in
self.handleBackgroundProcess(task: task as! BGProcessingTask)
}
} else {
// Fallback on earlier versions
}
return true
}
@available(iOS 13.0, *)
func handleBackgroundProcess(task:BGProcessingTask) {
schedularProcessTask()
bgTask(task: task)
}
@available(iOS 13.0, *)
func bgTask(task:BGProcessingTask) {
let predicate = NSPredicate(format: "timestamp <%@", NSDate(timeIntervalSinceNow: -24 * 60 * 60))
task.expirationHandler = {
BGTaskScheduler.shared.cancelAllTaskRequests()
}
let location = LocationObj()
let lat = location.lat ?? 0
let lon = location.lon ?? 0
let accuracy = location.accuracy
var taskId = "123"
let endpoint = CheckTaskGeolocationEndpoint(taskId:taskId, lat: lat, lon: lon, accuracy: accuracy)
endpoint.apiCall { (result, error) in
if error?.success ?? false {
if result?.autoExit == true {
ReminderNotificationManager.shared.scheduleLocalNotification(tite: "You are not in the polygon",
body: "Task is over")
BGTaskScheduler.shared.cancelAllTaskRequests()
}else {
ReminderNotificationManager.shared.scheduleLocalNotification(tite: "You are in the polygon",
body: "All good")
print(predicate)
/// task was complete and wait when task is run again
task.setTaskCompleted(success: true)
}
} else {
/// task was complete and wait when task is run again
task.setTaskCompleted(success: true)
}
}
}SceneDelegate.swift
func sceneDidEnterBackground(_ scene: UIScene) {
schedularProcessTask()
}
@available(iOS 13.0, *)
func schedularProcessTask() {
let request = BGProcessingTaskRequest(identifier: "com.transistorsoft.process")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
request.requiresNetworkConnectivity = true
do {
try BGTaskScheduler.shared.submit(request)
}catch {
print("Could not schedule app refresh \(error)")
}
}发布于 2021-02-17 20:37:32
您可能需要的工具是startMonitoring(for:),用于监视区域内的某个区域。你不能在某个时间间隔可靠地启动你的应用程序,如果你这样做了,这将是非常糟糕的电池寿命。但是区域监控是电池高效的,一般情况下,操作系统会在需要的时候启动你。
您可以探索的其他工具包括startMonitoringSignificantLocationChanges、push通知和iBeacons。但对于这一特殊问题,区域监测可能是最有效的。
https://stackoverflow.com/questions/66248356
复制相似问题