gpt4 book ai didi

ios - 从 HealthStore 读取心率

转载 作者:行者123 更新时间:2023-11-30 12:02:42 28 4
gpt4 key购买 nike

我正在尝试从 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
}

现在我的函数格式示例:

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())
}

你能帮我吗?

最佳答案

问题是我的谓词不正确。

这是我使用的正确谓词的示例。它将结果限制为最近 7 天。

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: [])

关于ios - 从 HealthStore 读取心率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com