使用下面的代码,我在Apple Watch上查询distanceWalkingAndRunning
个样本,我想返回给我(即在用户移动时实时调用完成处理程序),但是,在测试中...当我移动时,不会调用完成处理程序,只有当我抬起手腕并激活手表时才会调用它?如果可能的话,我希望在后台收集这些数据。在锻炼开始时会触发查询,这些都与awake
或willActivate
函数无关?
func startWalkingRunningQuery(from startDate: Date, updateHandler: @escaping ([HKQuantitySample]) -> Void) {
let typeIdentifier = HKQuantityTypeIdentifier.distanceWalkingRunning
startQuery(ofType: typeIdentifier, from: startDate) { _, samples, _, _, error in
guard let quantitySamples = samples as? [HKQuantitySample] else {
print("Distance walking running query failed with error: \(String(describing: error))")
return
}
updateHandler(quantitySamples)
}
}
//Generic helper function
private func startQuery(ofType type: HKQuantityTypeIdentifier, from startDate: Date, handler: @escaping
(HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void) {
let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: nil, options: .strictStartDate)
let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate, devicePredicate])
let quantityType = HKObjectType.quantityType(forIdentifier: type)!
let query = HKAnchoredObjectQuery(type: quantityType, predicate: queryPredicate, anchor: nil,
limit: HKObjectQueryNoLimit, resultsHandler: handler)
query.updateHandler = handler
healthStore.execute(query)
activeDataQueries.append(query)
}