如何根据 Apple Health 中的时间戳查询 healthkit 数据? [关闭]
Posted
技术标签:
【中文标题】如何根据 Apple Health 中的时间戳查询 healthkit 数据? [关闭]【英文标题】:How to query healthkit data based upon timestamp in Apple health? [closed] 【发布时间】:2020-12-10 02:45:53 【问题描述】:在特定时间段内收集activity
信息(例如Calories Burned
、Exercise time
)的最佳方法是什么?
任何方法或提示都是可以理解的。谢谢
【问题讨论】:
【参考方案1】:您可以在 HealthKit 中使用查询类。例如:
let calendar = NSCalendar.currentCalendar()
let interval = NSDateComponents()
interval.day = 7
// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate())
let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3
guard let anchorDate = calendar.dateFromComponents(anchorComponents) else
fatalError("*** unable to create a valid date from the given components ***")
guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else
fatalError("*** Unable to create a step count type ***")
// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
quantitySamplePredicate: nil,
options: .CumulativeSum,
anchorDate: anchorDate,
intervalComponents: interval)
// Set the results handler
query.initialResultsHandler =
query, results, error in
guard let statsCollection = results else
// Perform proper error handling here
fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
let endDate = NSDate()
guard let startDate = calendar.dateByAddingUnit(.Month, value: -3, toDate: endDate, options: []) else
fatalError("*** Unable to calculate the start date ***")
// Plot the weekly step counts over the past 3 months
statsCollection.enumerateStatisticsFromDate(startDate, toDate: endDate) [unowned self] statistics, stop in
if let quantity = statistics.sumQuantity()
let date = statistics.startDate
let value = quantity.doubleValueForUnit(HKUnit.countUnit())
// Call a custom method to plot each data point.
self.plotWeeklyStepCount(value, forDate: date)
healthStore.executeQuery(query)
您需要根据自己的情况使用这些代码。
【讨论】:
以上是关于如何根据 Apple Health 中的时间戳查询 healthkit 数据? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
Apple Health Kit 错误域 = com.apple.healthkit 代码 = 5“未确定授权”
如何使用第三方应用在 Apple Watch 中的活动移动环中添加贡献