[英]BG Processing task
我正在尝试在我的应用程序中使用 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)")
}
}
您可能需要的工具是startMonitoring(for:)
以在区域内进行监视。 你不能在某个时间间隔可靠地启动你的应用程序,如果你这样做了,那将对电池寿命非常不利。 但是区域监控是省电的,通常操作系统会在需要时启动你。
您可以探索的其他工具是startMonitoringSignificantLocationChanges
、推送通知和 iBeacons。 但对于这个特定问题,区域监控可能是最有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.