- 为重量创建一个 HKSampleQuery(但不要执行它)
- 创建并执行一个 HKObserverQuery on weight
- 在观察者查询的updateHandler中,执行权重样本查询
第一次执行示例查询时工作正常。
下次执行示例查询时,出现异常:“...'NSInvalidArgumentException',原因:'您无法启动已经处于活动状态的查询'”
如果每次在观察者更新处理程序中创建一个新的示例查询,然后执行,它就可以正常工作。
似乎我应该能够重新使用示例查询的第一个实例;没有任何相反的记录。
class HealthDemoC {
let store = HKHealthStore()
let wtType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!
var wtObserverQ: HKObserverQuery! = nil
var wtSampleQ: HKSampleQuery! = nil
init() {
print("init: HealthDemoC")
// !! only instantiating the query here and then executing repeatedly in observerUpdateHandler fails
wtSampleQ = HKSampleQuery(sampleType: wtType, predicate: nil, limit: 0, sortDescriptors: nil, resultsHandler: wtResultsHandler)
wtObserverQ = HKObserverQuery(sampleType: wtType as HKSampleType, predicate: nil, updateHandler: observerUpdateHandler)
store.executeQuery(wtObserverQ)
}
func observerUpdateHandler (query: HKObserverQuery,
completion: HKObserverQueryCompletionHandler,
error: NSError?) {
print("clbk: observerUpdateHandler")
// instantianting a new query with each call to observerUpdateHandler works
// wtSampleQ = HKSampleQuery(sampleType: wtType, predicate: nil, limit: 0, sortDescriptors: nil, resultsHandler: wtResultsHandler)
store.executeQuery(wtSampleQ)
completion()
}
func wtResultsHandler(query: HKSampleQuery, results: [HKSample]?, error: NSError?) {
print("clbk: wtResultsHandler - \(results!.count)) results")
// stopping the query doesn't prevent the exception
// store.stopQuery(query)
}
}