Swift - Healthkit 的 HKSampleQuery 示例

Swift - HKSampleQuery Samples of Healthkit

我正在尝试 return 记录最近 7 天的心跳样本。我认为我的方法不错,但我仍然不太确定我的查询部分。这是我到目前为止所做的。唯一被打印的想法是

95 count/min 90EBAB07-9CAB-445E-A967-4BD5E8AADAA4 "User’s Apple Watch" (5.1.3), "Watch3,2" (5.1.3)"Apple Watch" metadata: {
    HKMetadataKeyHeartRateMotionContext = 0;
} (2019-02-22 21:51:31 -0400 - 2019-02-22 21:51:31 -0400)

这是我的查询:

    func getTodaysHeartRate(completion: (@escaping (HKQuantitySample) -> Void)) {

        let sortDescriptor = NSSortDescriptor(
            key: HKSampleSortIdentifierEndDate,
            ascending: false)

        let heartRateType = HKSampleType.quantityType(forIdentifier: .heartRate)!
        let endDate = Date()
        let startDate = endDate.addingTimeInterval(-1.0 * 60 * 60 * 24)
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])

        let query = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor])
        { (query, result, error) -> Void in
        DispatchQueue.main.async {
        guard let result = result,
            let resultCount = result.first as? HKQuantitySample else {
            print("Failed to fetch heart rate")
            return
            }
            completion(resultCount)
        }
        }
    healthStore.execute(query)
}

    @IBOutlet weak var heartRate: UILabel!
    @IBAction func getHeartRate(_ sender: Any) {
        getTodaysHeartRate { (result) in
            print("\(result)")
            DispatchQueue.main.async {
                self.heartRate.text = "\(result)"
            }
    }

这应该 return 你最近 7 天。希望对您有所帮助!

let startDate = Date() - 7 * 24 * 60 * 60
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])