gpt4 book ai didi

ios - 当应用程序处于后台模式时,HealthKit Observer 不工作

转载 作者:行者123 更新时间:2023-11-29 01:59:16 25 4
gpt4 key购买 nike

我关注了Apple Docs stackoverflow 上的几个线程介绍了如何实现从 Health Store 后台获取数据。到目前为止我已经:

  • 已将 HealthKit 权利添加到我的 appID
  • 添加了必需的背景模式
  • 按照 Apple 的建议将代码添加到 AppDelegate.swift(下面的代码段不遵循 OOP,只是为了便于在此说明)

这是我的代码(快速):如果您的答案是在 Obj-C 中并且有效,请也​​说明,我将不得不翻译它,但这没问题。

AppDelegate.swift

var healthStore: HKHealthStore?
var bpmSamples: [HKQuantitySample]?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let dataTypesToWrite = [ ]
let dataTypesToRead = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)
]
if self.healthStore == nil {
self.healthStore = HKHealthStore()
}
self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite as [AnyObject]) as Set<NSObject>,
readTypes: NSSet(array: dataTypesToRead) as Set<NSObject>, completion: {
(success, error) in
if success {
self.addQueryObserver()
println("User completed authorisation request.")
} else {
println("The user cancelled the authorisation request. \(error)")
}
})
return true
}

func addQueryObserver(){
let sampleType =
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)

let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
query, completionHandler, error in
if error != nil {
// Perform Proper Error Handling Here...
println("*** An error occured while setting up the stepCount observer. \(error.localizedDescription) ***")
abort()
}
println("query is running")

self.performQueryForHeartBeatSamples()
completionHandler()
}
healthStore?.executeQuery(query)
healthStore?.enableBackgroundDeliveryForType(sampleType, frequency:.Immediate, withCompletion:{
(success:Bool, error:NSError!) -> Void in
let authorized = self.healthStore!.authorizationStatusForType(sampleType)
println("HEALTH callback success", success)
println("HEALTH callback authorized", sampleType)
})
if HKHealthStore.isHealthDataAvailable() == false {
println("HEALTH data not available")
return
} else {
println("HEALTH OK")
self.performQueryForHeartBeatSamples()
}
}
// MARK: - HealthStore utility methods
func performQueryForHeartBeatSamples() {
let endDate = NSDate()
let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth, value: -2, toDate: endDate, options: nil)

var heartRate : HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)

let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
let query = HKSampleQuery(sampleType: heartRate, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: {
(query, results, error) in
if results == nil {
println("There was an error running the query: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.bpmSamples = results as? [HKQuantitySample]
let heartRateUnit: HKUnit = HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit())
if self.bpmSamples?.count > 0 {
if let sample = self.bpmSamples?[self.bpmSamples!.count - 1] {
println(sample.quantity!.description)
let quantity = sample.quantity
var value = quantity.doubleValueForUnit(heartRateUnit)
println("bpm: \(value)")
}
}
else {
println("No Data")
}
}
})
self.healthStore?.executeQuery(query)
}

所以,问题是我只有在手动将应用程序从后台恢复到事件状态时才会收到更新。在后台模式下,HKObserverQuery 似乎不适用于我。

有什么建议吗?

最佳答案

根据我的经验,频率“.Immediate”效果不佳。查询的处理程序被插入到后台队列中。如果频繁添加匹配样本或 iOS 繁忙,则即时频率效果不佳。

此外,您不能在HKObserverQuery 中使用HKSampleQueryHKObserverQueryupdateHandler 可能有效,但 HKSampleQueryresultHandler 无效。观察者查询的处理程序可以在后台模式下执行,但样本查询的处理程序不能在后台模式下执行。

你应该知道只有HKObserverQuery可以在后台使用

关于ios - 当应用程序处于后台模式时,HealthKit Observer 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com