从HealthStore读取心率

时间:2017-10-30 13:30:49

标签: ios swift hkhealthstore

我正在尝试从Healthkit中检索心率信息。

我的个人资料中有一些心率数据。

这是我的问题:

private func createStreamingQuery() -> HKQuery {
    let predicate = HKQuery.predicateForSamples(withStart: NSDate() as Date, end: nil, options: [])

    let query = HKAnchoredObjectQuery(type: heartRateType, predicate: predicate, anchor: nil, limit: Int(HKObjectQueryNoLimit)) {
        (query, samples, deletedObjects, anchor, error) -> Void in

        self.formatSamples(samples: samples)

    }

    query.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
        self.formatSamples(samples: samples)
    }

    return query
}

现在我的函数格式为Samples:

private func formatSamples(samples: [HKSample]?) {
    guard let heartRateSamples = samples as? [HKQuantitySample] else { return }

        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValue(for: self.heartRateUnit)

        print("HeartRate: \(value)")
}

我已经调试了,我发现在“formatSamples”的第一行代码中,“samples”列表有很多值,

 guard let heartRateSamples = samples as? [HKQuantitySample] else { return } 

但是当我尝试获取此列表的第一个值时,突然我的列表为空,它结束了该功能。 这里 - >

guard let sample = heartRateSamples.first else{return}

我不明白为什么样本列表会从一行清空到下一行。

执行查询。

@IBAction func readHeartRate(_ sender: Any) {
    self.healthStore.execute(self.createStreamingQuery())
}

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

问题是我的谓词不正确。

这是我使用的正确谓词的示例。它将结果限制在过去七天。

let calendar = NSCalendar.current;
let now = NSDate();
let sevenDaysAgo = calendar.date(byAdding: .day, value: -7, to: now as Date);
let startDate = calendar.startOfDay(for: sevenDaysAgo!);

let predicate = HKQuery.predicateForSamples(withStart: startDate as Date, end: now as Date, options: [])