设置 HKAnchoredObjectQuery 以便我只接收自上次查询以来的更新?

Setting up an HKAnchoredObjectQuery so that I only receive updates since the last time I queried?

我正在尝试设置一个 HKAnchoredObjectQuery,它只会提供我上次进行此查询时的结果,但我无法理解设置 HKQueryAnchor 的逻辑以及如何我坚持了吗?在 Apple's sample code 中,它们不显示 HKQueryAnchor 的初始声明。我是否需要在本地存储上次下载样本的日期并从该日期构建锚点?此代码位于 returns HealthKit 中的每个示例下方。

func updateWorkouts(completionHandler: @escaping () -> Void) {

        var anchor: HKQueryAnchor?

        let sampleType =  HKObjectType.workoutType()
        let workoutPredicate = HKQuery.predicateForWorkouts(with: .hockey)
        let sourcePredicate = HKQuery.predicateForObjects(from: HKSource.default()) //limit query to only this app
        let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [workoutPredicate, sourcePredicate])

        let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: compound, anchor: anchor, limit: HKObjectQueryNoLimit) { [unowned self] query, newSamples, deletedSamples, newAnchor, error in

            self.handleNewWorkouts(newWorkoutsAsSamples: newSamples!, deleted: deletedSamples!)

            anchor = newAnchor

            completionHandler()
        }
        healthStore.execute(anchoredQuery)


    }

在初始化 HKAnchoredObjectQuery 时,您需要提供 nil 或您从之前执行的查询中收到的锚点对象。你不能自己直接构造一个 HKQueryAnchor 。要在应用程序启动之间保留锚点,您可以使用 NSKeyedArchiver 在持久存储中对其进行编码。通常将生成的编码 NSData 存储在 NSUserDefaults.