我正在尝试设置一个HKAnchoredObjectQuery,它将只传递上次我进行此查询时的结果,但我无法理解设置hkquerychor的逻辑以及如何保持它?在Apple's sample code中,它们不显示HKQueryAnchor的初始声明。是否需要在本地存储上次下载的示例的日期,并从该日期开始构造锚定?下面的代码返回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中。

09-03 23:54