【发布时间】:2021-05-20 17:17:03
【问题描述】:
我正在尝试在我的应用程序中使用 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)")
}
}
【问题讨论】:
-
“我需要在用户关闭应用程序后,此代码每 15 分钟运行一次,并向服务器发送数据。”这是不可能的。 iOS 中没有允许您在已知时间段执行操作的机制。你可以要求它,但操作系统不承诺它(通常不会给你)。您可以获得的最接近的是发送推送通知,但他们不承诺启动您的应用程序,但通常会。如果你需要这个,你需要重新设计成不需要它。
-
您绝对不能每 15 分钟跟踪一次用户的位置。您可以打开完整的位置跟踪,这是相当耗电的,并且需要持续的用户许可。或者您可以使用
startMonitoringSignificantLocationChanges,它可能更接近您要查找的内容,但仅适用于相当大的区域(~500m,但可以更多)。或者您可以使用 iBeacon(但您必须部署 iBeacon)。 -
@RobNapier 好的,谢谢)如果我将区域设置为
startMonitoring (for: CLRegion),并且用户关闭了应用程序,我可以跟踪他何时离开该位置并将其发送到服务器吗? -
是的,CLRegion 监控通常也非常强大。它的功耗也非常低。
-
@RobNapier 好的,你可以把这个写成答案,我会把它标记为正确
标签: ios swift iphone background scheduled-tasks