在后台获取苹果健康数据



我想在后台从苹果健康获取数据。。我不知道在哪里调用我的函数updateOnBackground

我看了相关的主题,我现在有这个:

func updateOnBackground() {

let quantityType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
self.healthStore.enableBackgroundDelivery(for: quantityType, frequency: .immediate) { (success, error) in
if let error = error {
print("(error)")
}
if success {
print("background delivery enabled")
}
}

let query = HKObserverQuery(sampleType: quantityType, predicate: nil) { (query, completionHandler, error) in
self.updateData(){
completionHandler()
}
}
healthStore.execute(query)

}

这是在应用程序激活时获取数据的功能:

class func getMostRecentSample(for sampleType: HKSampleType,
completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) {
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options: .strictEndDate)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let limit = 1
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) { (query, samples, error) in
DispatchQueue.main.async {
guard let samples = samples,

let mostRecentSample = samples.first as? HKQuantitySample else {
completion(nil, error)

return
}
//print(samples)
completion(mostRecentSample, nil)
}

}

HKHealthStore().execute(sampleQuery)
}
func updateData(completionHandler: @escaping () -> Void) {
let sampleType =  HKQuantityType.quantityType(forIdentifier: .heartRate)!
HealthData.getMostRecentSample(for: sampleType) { (sample, error) in
self.handleNewData(new: sample!)
completionHandler()
}
}

func handleNewData(new: HKQuantitySample) {
print(new)

}

我认为这里不需要getMostCentrSample函数,否则我怎么能做得更好呢?

根据Apple文档,用于观察查询和后台交付https://developer.apple.com/documentation/healthkit/hkhealthstore/1614175-enablebackgrounddelivery没有比中的AppDelegate.swift更好的地方了

func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
updateOnBackground()
return true
}

这将保证您的应用程序将收到来自Apple Health的新数据生成通知。对于某些类型,更新的频率可能有所不同。例如,如果你试图以.immediate频率获取步骤,这将不起作用——它只会在一小时后发生(由苹果健康应用程序自动决定(。

你可以试试我的CocoaPod。以下是链接:https://cocoapods.org/pods/HealthKitReporter.它是HealthKit框架之上的一个包装器,用于简化读/写操作+观察。

您还可以(在pod中(查看HKAnchoredObjectQuery的实现。它类似于观察者查询+样例查询,后者也是一个长时间运行的查询。看看这里https://developer.apple.com/documentation/healthkit/hkanchoredobjectquery

最新更新