如何在应用程序处于后台时查询HealthKit(HKWorkout)更新?

时间:2018-04-02 16:05:23

标签: ios swift background-process appdelegate health-kit

编辑添加我更新的代码,我基于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!)")
}

1 个答案:

答案 0 :(得分:0)

原来这个代码有效,只是我在模拟器中进行测试,显然Observer Query在模拟器中运行时会NOT触发,但在设备上运行时会触发