我可以从健康工具包中得到我的健康数据清单。我使用下面的代码获取我今天的步数:
func getTodaysSteps(completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay,
end: now,
options: .strictStartDate
)
let query = HKStatisticsQuery(
quantityType: stepsQuantityType,
quantitySamplePredicate: predicate,
options: .cumulativeSum
) { _, result, _ in
guard let result = result, let sum = result.sumQuantity() else {
completion(0.0)
return
}
completion(sum.doubleValue(for: HKUnit.count()))
}
healthStore.execute(query)
}但我还有一份我弟弟的健康数据,他邀请我在我真正的设备里看他的健康数据。现在我无法阅读/获得他的健康数据。有什么办法能弄明白吗。
任何解决办法都是很棒的.!
发布于 2022-01-03 00:10:37
如果您想要步骤计数,则不需要静态查询。试试这个;
let comp: DateComponents = Calendar.current.dateComponents([.year, .month], from: Date())
let startOfMonth = Calendar.current.date(from: comp)!
searchPredicate = HKQuery.predicateForSamples(withStart: startOfMonth, end: Date(), options: .strictStartDate)
let sampleQuery = HKSampleQuery(sampleType: .stepCount, predicate: searchPredicate, limit: limit, sortDescriptors: [])
{
(query, result, error) in
if error != nil
{
completion(-1)
}
self.hkSampleRecs.removeAll(keepingCapacity: true)
if result != nil
{
for r in result!
{
self.hkSampleRecs.append(r)
}
}
completion(self.hkSampleRecs.count)
}
healthStore.execute(sampleQuery)请注意,我还没有向您展示我使用的完成设置。我还将记录存储在我在其他地方定义的数组(hkSampleRecs)中。这个例子也只给出到目前为止这个月的数据。根据需要更改日期。
https://stackoverflow.com/questions/70549158
复制相似问题