【发布时间】:2020-07-24 15:18:35
【问题描述】:
我正在尝试在后台检查一些 HealthKit 数据,并在满足某些条件时发送本地通知。
我添加了后台获取功能并将我的任务 ID 添加到 info.plist。
后台任务代码如下:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// other setups
self.setupHealthKit()
self.setupBackgroundTasks()
return true
}
fileprivate func setupHealthKit() {
HealthKitHelper.shared.executeObserverQuery(for: HealthKitTypes.activeEnergy,
predicate: nil)
.sink(receiveCompletion: {
completion in
switch completion {
case .failure(let error):
print("observer query execution failed with error: \(error.localizedDescription)")
EventLogger.BackgroundDelivery.logObserverQueryError(error: error.localizedDescription)
case .finished:
print("observer query executed.")
}
}, receiveValue: {
query, handler in
// we have some updates
EventLogger.BackgroundDelivery.logObserverQueryResultInBackground()
// check if there is a new sleep session
let queue = OperationQueue()
let operations = self.getBackgroundOperations()
let last = operations.last!
last.completionBlock = {
handler()
}
queue.addOperations(operations, waitUntilFinished: false)
})
.store(in: &self.subscriberStore)
HealthKitHelper.shared.enableBackgroundDelivery(for: HealthKitTypes.activeEnergy,
frequency: .hourly)
.sink(receiveCompletion: {
completion in
switch completion {
case .failure(let error):
print("failed to enable bg delivery with error: \(error.localizedDescription)")
case .finished:
print("delivery enable finished.")
}
}, receiveValue: {
status in
print("delivery enable success status: \(status)")
})
.store(in: &self.subscriberStore)
}
func setupBackgroundTasks() {
let status = BGTaskScheduler.shared.register(forTaskWithIdentifier: self.BACKGROUND_FETCH_TASK_ID,
using: nil) {
task in
self.handleBackgroundAppRefresh(task as! BGAppRefreshTask)
}
}
我只是在后台任务中发送本地通知,看看它是否有效。 现在我可以在调试器中运行后台任务,但它永远不会被系统执行。
而且我也不知道在后台获取新的健康包样本的最佳方法是什么。
【问题讨论】:
-
运气好能解决这个问题吗?这里有同样的问题..
-
我停止使用 combine 处理后台任务,它解决了问题。
标签: ios swift healthkit background-task