编辑添加我更新的代码,我基于WWDC 2016的最大化Healthkit谈话,但我仍然没有得到我的打印声明与新的锻炼,除非我打开应用程序?
我试图在iPhone上保存之后观察iPhone上的新训练。以下是我在didFinishLaunching
中运行的代码。为了测试它,我在我的iPhone App上运行Xcode ......构建并运行,然后导航回主屏幕。然后在我的手表上启动并保存锻炼,但是我的打印报告没有在控制台中打印。我错过了什么?
func startObservingNewWorkouts() {
let sampleType = HKObjectType.workoutType()
//1. Enable background delivery for workouts
self.healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
if let unwrappedError = error {
print("could not enable background delivery: \(unwrappedError)")
}
if success {
print("background delivery enabled")
}
}
//2. open observer query
let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { (query, completionHandler, error) in
self.updateWorkouts() {
completionHandler()
}
}
healthStore.execute(query)
}
func updateWorkouts(completionHandler: @escaping () -> Void) {
var anchor: HKQueryAnchor?
let sampleType = HKObjectType.workoutType()
let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: nil, anchor: anchor, limit: HKObjectQueryNoLimit) { [unowned self] query, newSamples, deletedSamples, newAnchor, error in
self.handleNewWorkouts(new: newSamples!, deleted: deletedSamples!)
anchor = newAnchor
completionHandler()
}
healthStore.execute(anchoredQuery)
}
func handleNewWorkouts(new: [HKSample], deleted: [HKDeletedObject]) {
print("new sample added = \(new.last.startTime!)")
}