Health Kit 开发

HealthKit是Apple公司在推出iOS 8 系统时一块推出的关于健康信息的框架,可以用它来分享健康和健身数据。

一、 关于Health App

​ 健康 app 重点关注四个方面:健身记录、睡眠状况、正念训练和营养摄入。

1.健身记录

​ 健康 app 会显示你已经完成的运动量,激励你继续努力。它集中了 iPhone 上的健身记录 (如行走的步数及距离) 和来自第三方健身 app 的数据。

2.睡眠状况

​ 良好的睡眠能帮助你的身体恢复精力。所以,每晚在固定时间上床睡觉,得到足够的休息能改善你的精神状态。无论是时钟 app 中的就寝功能,还是第三方睡眠配件,它们都可将信息反馈至健康 app,让你养成健康的睡眠习惯。

3.正念训练

​ 找个时间深呼吸几次,让思绪沉静下来,恰是舒缓压力、提升整体健康的上佳之道,这也正是正念训练的真正目的,健康 app 都会将数据整合起来,让你知道自己有多少时间是处于心境平静的状态。

4.营养摄入

​ 无论你是在计算碳水化合物、卡路里、咖啡因,还是其他重要的营养指标,健康 app 都可以方便地管理你的目标,查看你每天的饮食摄入状况。第三方 app 能帮你密切关注每一餐的饮食,由于这些数据都会在健康 app 中显示,你可以随时掌握自己的营养摄入状况是否达标。

5.其他

​ 健康 app 能轻松记录对你来说重要的各类数据,包括你的血压和血糖,以及你的体重和生殖健康记录。

二、关于Health Kit

​ 我们自己创建的app,在app中使用了HealthKit框架之后只要通过用户的授权,就可以在我们的app之中给健康分享数据或者从健康中获取数据。iPhone手机自身可以监控步数信息,会自动导入步数信息。但是其他信息或者设备需要配套的应用才能获取到数据并导入到HealthKit中并在健康中显示。

​ HealthKit不能在iPad中使用,而且它也不支持扩展。

三、Health Kit 在项目中的使用

1.在Target中的Capabilities打开 HealthKit功能

2.在info.plist文件中申请key

​ 读取权限 :Privacy - Health Share Usage Description

​ 写入权限:Privacy - Health Update Usage Description

3.导入HealthKit框架

4.应用注册权限

//判断是否支持Health Kit
if HKHealthStore.isHealthDataAvailable() {}
​
//读取权限集合
let healthKitTypesToRead = NSSet(array:[HKObjectType.quantityType(forIdentifier:HKQuantityTypeIdentifier.stepCount)!])
​
//写入权限集合
let healthKitTypesToWrite = NSSet(array:[HKObjectType.quantityType(forIdentifier:HKQuantityTypeIdentifier.bodyMassIndex)!])
​
//注册读写权限
healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite as? Set, read: healthKitTypesToRead as? Set) { (success, error) -> Void in

 completion(success,error as NSError?)
 }
  1. 授权数据
一.身体测量  [HKObjectType quantityTypeForIdentifier:……]
​
 1. HKQuantityTypeIdentifierBodyMassIndex  身高体重指数
 2. HKQuantityTypeIdentifierBodyFatPercentage 体脂率
 3. HKQuantityTypeIdentifierHeight 身高
 4. HKQuantityTypeIdentifierBodyMass 体重
 5. HKQuantityTypeIdentifierLeanBodyMass 去脂体重
​
二、健身数据  [HKObjectType quantityTypeForIdentifier:……]
​
 1. HKQuantityTypeIdentifierStepCount   步数
 2. HKQuantityTypeIdentifierDistanceWalkingRunning  步行+跑步距离
 3. HKQuantityTypeIdentifierDistanceCycling  骑车距离
 4. HKQuantityTypeIdentifierDistanceWheelchair  轮椅距离
 5. HKQuantityTypeIdentifierBasalEnergyBurned  静息能量
 6. HKQuantityTypeIdentifierActiveEnergyBurned  活动能量
 7. HKQuantityTypeIdentifierFlightsClimbed    已爬楼层
 8. HKQuantityTypeIdentifierNikeFuel     NikeFuel
 9. HKQuantityTypeIdentifierAppleExerciseTime  锻炼分钟数健身数据
 10.HKQuantityTypeIdentifierDistanceSwimming  游泳距离
 11.HKQuantityTypeIdentifierSwimmingStrokeCount 游泳冲刺次数
​
三、主要特征   [HKObjectType quantityTypeForIdentifier:……]
​
 1. HKQuantityTypeIdentifierHeartRate 心率
 2. HKQuantityTypeIdentifierBodyTemperature  体温
 3. HKQuantityTypeIdentifierBasalBodyTemperature 基础体温
 4. HKQuantityTypeIdentifierBloodPressureSystolic  收缩压
 5. HKQuantityTypeIdentifierBloodPressureDiastolic  舒张压
 6. HKQuantityTypeIdentifierRespiratoryRate  呼吸速率
​
四、数据结果   [HKObjectType quantityTypeForIdentifier:……]
​
 1. HKQuantityTypeIdentifierOxygenSaturation  血氧饱和度
 2. HKQuantityTypeIdentifierPeripheralPerfusionIndex 末梢灌注指数
 3. HKQuantityTypeIdentifierBloodGlucose 血糖
 4. HKQuantityTypeIdentifierNumberOfTimesFallen 摔倒次数
 5. HKQuantityTypeIdentifierElectrodermalActivity  皮电活动
 6. HKQuantityTypeIdentifierInhalerUsage 吸入剂用量
 7. HKQuantityTypeIdentifierBloodAlcoholContent  血液酒精浓度
 8. HKQuantityTypeIdentifierForcedVitalCapacity  最大肺活量|用力肺活量
 9. HKQuantityTypeIdentifierForcedExpiratoryVolume1 第一秒用力呼气量
 10.HKQuantityTypeIdentifierPeakExpiratoryFlowRate 呼气流量峰值
​
五、营养摄入    [HKObjectType quantityTypeForIdentifier:……]
​
 1. HKQuantityTypeIdentifierDietaryFatTotal 总脂肪
 2. HKQuantityTypeIdentifierDietaryFatPolyunsaturated  多元不饱和脂肪
 3. HKQuantityTypeIdentifierDietaryFatMonounsaturated 单元不饱和脂肪
 4. HKQuantityTypeIdentifierDietaryFatSaturated 饱和脂肪
 5. HKQuantityTypeIdentifierDietaryCholesterol 膳食胆固醇
 6. HKQuantityTypeIdentifierDietarySodium 钠
 7. HKQuantityTypeIdentifierDietaryCarbohydrates 碳水化合物
 8. HKQuantityTypeIdentifierDietaryFiber 纤维
 9. HKQuantityTypeIdentifierDietarySugar 膳食糖
 10.HKQuantityTypeIdentifierDietaryEnergyConsumed  膳食能量
 11.HKQuantityTypeIdentifierDietaryProtein 蛋白质
 12.HKQuantityTypeIdentifierDietaryVitaminA 维生素 A
 13.HKQuantityTypeIdentifierDietaryVitaminB6 维生素 B6
 14.HKQuantityTypeIdentifierDietaryVitaminB12 维生素 B12
 15.HKQuantityTypeIdentifierDietaryVitaminC 维生素 C
 16.HKQuantityTypeIdentifierDietaryVitaminD 维生素 D
 17.HKQuantityTypeIdentifierDietaryVitaminE 维生素 E
 18.HKQuantityTypeIdentifierDietaryVitaminK 维生素 K
 19.HKQuantityTypeIdentifierDietaryCalcium  钙
 20.HKQuantityTypeIdentifierDietaryIron 铁
 21.HKQuantityTypeIdentifierDietaryThiamin 硫铵
 22.HKQuantityTypeIdentifierDietaryRiboflavin 核黄素
 23.HKQuantityTypeIdentifierDietaryNiacin 烟酸
 24.HKQuantityTypeIdentifierDietaryFolate 叶酸
 25.HKQuantityTypeIdentifierDietaryBiotin 生物素
 26.HKQuantityTypeIdentifierDietaryPantothenicAcid 泛酸
 27.HKQuantityTypeIdentifierDietaryPhosphorus 磷
 28.HKQuantityTypeIdentifierDietaryIodine 碘
 29.HKQuantityTypeIdentifierDietaryMagnesium 镁
 30.HKQuantityTypeIdentifierDietaryZinc 锌
 31.HKQuantityTypeIdentifierDietarySelenium 硒
 32.HKQuantityTypeIdentifierDietaryCopper 铜
 33.HKQuantityTypeIdentifierDietaryManganese 锰
 34.HKQuantityTypeIdentifierDietaryChromium 铬
 35.HKQuantityTypeIdentifierDietaryMolybdenum 钼
 36.HKQuantityTypeIdentifierDietaryChloride 氯化物
 37.HKQuantityTypeIdentifierDietaryPotassium 钾
 38.HKQuantityTypeIdentifierDietaryCaffeine 咖啡因
 39.HKQuantityTypeIdentifierDietaryWater 水
 40.HKQuantityTypeIdentifierUVExposure 紫外线指数
​
六、生殖健康   [HKObjectType categoryTypeForIdentifier:……];
​
 1. HKCategoryTypeIdentifierSleepAnalysis 睡眠分析
 2. HKCategoryTypeIdentifierAppleStandHour 站立小时
 3. HKCategoryTypeIdentifierCervicalMucusQuality 宫颈粘液质量
 4. HKCategoryTypeIdentifierOvulationTestResult 排卵测试结果
 5. HKCategoryTypeIdentifierMenstrualFlow 月经
 6. HKCategoryTypeIdentifierIntermenstrualBleeding 点滴出血
 7. HKCategoryTypeIdentifierSexualActivity 性行为
 8. HKCategoryTypeIdentifierMindfulSession 正念分钟数
​
七、本人信息   [HKObjectType characteristicTypeForIdentifier:……];
​
 1. HKCharacteristicTypeIdentifierBiologicalSex 性别 
 2. HKCharacteristicTypeIdentifierBloodType 血型 
 3. HKCharacteristicTypeIdentifierDateOfBirth 出生日期
 4. HKCharacteristicTypeIdentifierFitzpatrickSkinType 日光反应型皮肤类型
​
八、活动能量  
[HKObjectType workoutType];
​
九、健身记录
[HKObjectType activitySummaryType];
​
十、健康记录请求  [HKObjectType documentTypeForIdentifier:……];
​
 1. HKDocumentTypeIdentifierCDA 健康记录请求
​
十一.Correlation(HKCorrelationType)    [HKObjectType correlationTypeForIdentifier:……];   不可读不可写
​
 1. HKCorrelationTypeIdentifierBloodPressure 血压 
 2. HKCorrelationTypeIdentifierFood 食物

6.读取数据

方法1

//  构建过滤方式对象
 let mostRecentPredicate = HKQuery.predicateForSamples(withStart: nowDay, end:nextDay, options: HKQueryOptions())
//  排序
 let startDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
 let endDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierEndDate, ascending: false)
//读取数据类型 
 let stepsSampleType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
 let stepsUnit = HKUnit.count()

//创建样本对象 
 let sampleQuery = HKSampleQuery(sampleType: stepsSampleType!,predicate: mostRecentPredicate,limit: 0,sortDescriptors:[startDescriptor,endDescriptor]) {(sampleQuery, samples, error) in

 if samples != nil{
 var sumSteps:Double = 0.0
 for sample in samples as! [HKQuantitySample]
 {
 let steps  = sample.quantity.doubleValue(for: stepsUnit)
 let date  = sample.startDate
 sumSteps += steps
 print("来源:\(sample.source.bundleIdentifier)")
 }
 let stepModel = HealthStepModel()
 stepModel.step = sumSteps
 DispatchQueue.main.async(execute: { () -> Void in
 completion(stepModel,nil)
 });
 }else{
 DispatchQueue.main.async(execute: { () -> Void in
 completion(nil,error as NSError?)
 });
 }
 }
​
 healthKitStore.execute(sampleQuery)

参数介绍:
SampleType:使用HKQuantityType进行封装,表示查询的数据的类型, predicate:表示过滤方式,可以传nil, limit:查询返回的数据数量,可以为1, sortDescriptors:排序方式

方法2

//时间
let calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents = (calendar asNSCalendar).components([.day, .month, .year, .weekday], from: Date())
anchorComponents.hour = 0
let anchorDate = calendar.date(from: anchorComponents)
​
//数据类型
let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
​
//查询条件
let query = HKStatisticsCollectionQuery(quantityType: quantityType!,quantitySamplePredicate: nil,options: [.cumulativeSum,.separateBySource],anchorDate: anchorDate!,intervalComponents: interval)
​
// 设置回调事件
query.initialResultsHandler = {query, results, error in
​
 if error != nil {
​
 DispatchQueue.main.async(execute: { () -> Void in 
 completion(0,error asNSError?)
 });
​
 return
 }
​
 //时间
 let todayString = healthDateformatter.string(from: Date())
 let todayDate = healthDateformatter.date(from: todayString )
 let todayDateString =  (DateHandle.getLongFrom(todayDate)  asNSString).doubleValue/1000.0
 let pastDateString = (DateHandle.getLongFrom(todayDate) asNSString).doubleValue/1000.0 - 7*24*60*60 - 1
 let endDate = Date()
 let startDate = (calendar asNSCalendar).date(byAdding: NSCalendar.Unit.day, value: -7, to: endDate, options: NSCalendar.Options.init(rawValue: 0))
​
 //遍历
 results!.enumerateStatistics(from: startDate!, to:  endDate) {statistics, stop in
​
 if let quantity = statistics.sumQuantity() {
​
 _ = statistics.startDate
​
 let value = Int(quantity.doubleValue(for: HKUnit.count()))
​
 print("-----\(value)")
​
 DispatchQueue.main.async(execute: { () -> Void in
​
 completion(value,error asNSError?)
​
 });
​
 }
 }
}
​
healthKitStore.execute(query)

7.写入数据

// 创建步数数据对象
let stepUnit = HKUnit.count()
let stepCount = 1000
let stepQuantity = HKQuantity(unit: stepUnit, doubleValue: stepCount)
​
//创建样本对象
let stepQuery = HKQuantitySample(type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!, quantity: stepQuantity, start: startDate, end: endDate)
​
//写入数据
healthKitStore.save(stepQuery, withCompletion: { (success, error) -> Void in })

参考:

https://www.jianshu.com/p/f2f4a89cf4ed

https://www.jianshu.com/p/020e62b581ad

https://www.jianshu.com/p/ebe14a97525a

你可能感兴趣的:(Health Kit 开发)