ios - iOS后台任务从未启动
问题描述
此代码应该定期安排后台任务。
在设备上运行时,我从来没有看到“后台刷新已启动”日志可以证明系统已经安排了任务。
其他一切运行良好。
当我通过在控制台中输入来使用“强制后台任务启动技巧”时,e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"TaskIdentifier"]
我确实看到了正在执行的任务。
我在目标功能中激活了后台获取和后台处理。
那么为什么系统不安排任务呢?
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
MSLogger.debug("Application Event : didFinishLaunchingWithOptions")
// Register the background refresh handler and schedule it
registerForBackgroundRefresh()
scheduleNextRefresh()
return true
}
//------------------------------------------------------------------------------------------------------------------
// MARK: - Background refresh management
let backgroundTaskIdentifier = "TaskIdentifier"
func registerForBackgroundRefresh() {
let crd = BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier,
using: nil) {
task in
self.handleBackgroundRefresh(task: task as! BGAppRefreshTask)
}
MSLogger.debug("task registration : \(crd)")
}
func scheduleNextRefresh() {
// Schedule the next refresh for within 2 hours
let request = BGAppRefreshTaskRequest(identifier: backgroundTaskIdentifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 30 /*2 * 3600##*/)
do {
try BGTaskScheduler.shared.submit(request)
MSLogger.debug("submit background task request")
} catch {
MSLogger.debug("Could not schedule app refresh: \(error.localizedDescription)")
}
}
func handleBackgroundRefresh(task: BGAppRefreshTask) {
MSLogger.debug("background refresh started")
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let operation = BlockOperation {
// Do something
}
task.expirationHandler = {
// After all operations are cancelled, the completion block below is called to set the task to complete.
queue.cancelAllOperations()
self.scheduleNextRefresh()
}
operation.completionBlock = {
task.setTaskCompleted(success: operation.isCancelled)
self.scheduleNextRefresh()
}
queue.addOperation(operation)
}
}
解决方案
推荐阅读
- javascript - 使用JS检测用户是否在中国防火墙后面
- python - 烧瓶 api 不会识别它生成并给出的令牌是有效的
- javascript - 使用 Plotly 进行数据透视 - 无法设置区域设置
- python - 在 Django 中显示类别的子类别
- graphql - 如何使用 Apollo Server DataSource 调用 GraphQL API
- arrays - 如何从承诺中获取数组的长度?
- sitecore - Sitecore Experience Analytics 致命错误
- google-analytics - 无法在来自 GetResponse 的 Google Analytics(分析)数据中进行跟踪
- arrays - 创建一个字符串数组以使用 C 中与字符串相关的函数对它们运行测试
- java - 当logcat在android studio中不存在的行中显示错误时该怎么办