我正在开发一款步骤应用。我想从健康应用程序中检索Healthkit数据,但我不知道该怎么做。我在网上找不到任何东西。我想从健康应用程序中获取步骤数据。
答案 0 :(得分:6)
申请许可请求
if HKHealthStore.isHealthDataAvailable() {
var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite()
var readDataTypes: Set<AnyHashable> = self.dataTypesToRead()
self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in
if !success {
print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: \(error). If you're using a simulator, try it on a device.")
return
}
})
}
写入数据
func dataTypesToWrite() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
return Set<AnyHashable>([heightType, weightType, systolic, dystolic])
}
从健康套件中读取数据
func dataTypesToRead() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling)
var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
如果你想获得上周的步数,那么你可以按照下面的代码
self.healthStore = HKHealthStore()
var calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents?.hour = 0
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents)
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
// Create the query
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in
if error != nil {
// Perform proper error handling here
print("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
}
var endDate = Date()
var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0)
// Plot the daily step counts over the past 7 days
results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in
var quantity: HKQuantity? = result.sumQuantity()
if quantity != nil {
var date: Date? = result.startDate
var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count())
totalStepsCount = String(format: "%.f", value)
DispatchQueue.main.async(execute: {() -> Void in
self.calculateStepCountAndShow()
})
print("\(date): \(value)")
}
})
}
self.healthStore.executeQuery(query)
}
答案 1 :(得分:1)
互联网上有很多教程可以使用healthkit
在您的应用中设置healthkit并获取权限,请参阅其中一个教程
例如,如果我们想要检索睡眠分析数据,
func retrieveSleepAnalysis() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep"
print("Healthkit sleep: \(sample.startDate) \(sample.endDate) - value: \(value)")
}
}
}
}
// finally, we execute our query
healthStore.executeQuery(query)
}
}
答案 2 :(得分:0)
您需要从项目healthkit
启用capabilities
然后,您将完成authentication
流程,然后您将开始实施query
以使用HKSampleQuery
检索数据,请关注this tutorial
由于代码很长,所以包含在这里:)