我們應用內可能會應用蘋果自帶的健康來讀取一些數據,如:每日的步數、活動能量、游泳距離等等。
首先介紹一下 HealthKit, HealthKit是Apple公司在推出iOS 8 系統時一塊推出的關于健康信息的框架。如果iPhone手機系統升級到iOS8之后就會發現多了一個健康-app,這就是Apple提供的一個記錄用戶健康信息的app,可以用它來分享健康和健身數據。還可以指定數據的來源,比如我們自己創建一個app,在我們的app中使用了HealthKit框架之后只要經過用戶的認證,就可以在我們的app之中給健康分享數據或者從健康中獲取數據。
HealthKit可以與健身設備一起工作,iPhone手機自身可以監控步數信息,會自動導入步數信息。但是其他信息或者設備需要配套的應該才能獲取到數據并導入到HealthKit中并在健康中顯示。
HealthKit不能再iPad中使用,而且它也不支持擴展。
其次,我們說一下如何使用 HealthKit。
1、在應用中打開 HealthKit功能
2、在info.plist文件中申請key
讀取權限 :
Privacy - Health Share Usage Description
寫入權限:
Privacy - Health Update Usage Description
3、導入#import <HealthKit/HealthKit.h>框架
4、應用授權
//HealthKit中的管理者
HKHealthStore *store = [[HKHealthStore alloc] init];
//訪問權限類型
HKQuantityType *quType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *set = [NSSet setWithObject:quType];
//參數一是寫入操作。參數二是讀取操作
[store requestAuthorizationToShareTypes:set readTypes:set completion:^(BOOL success, NSError * _Nullable error) {
NSLog(@"success == %d ,error == %@" , success , error);
}];
上面的授權僅僅是可以訪問步數,其他的授權還有這些:
1)、數量樣本(HKQuantityType)
調用方法 :
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
-
身體測量
1. HKQuantityTypeIdentifierBodyMassIndex 身高體重指數 2. HKQuantityTypeIdentifierBodyFatPercentage 體脂率 3. HKQuantityTypeIdentifierHeight 身高 4. HKQuantityTypeIdentifierBodyMass 體重 5. HKQuantityTypeIdentifierLeanBodyMass 去脂體重
*健身數據
1. HKQuantityTypeIdentifierStepCount 步數
2. HKQuantityTypeIdentifierDistanceWalkingRunning 步行+跑步距離
3. HKQuantityTypeIdentifierDistanceCycling 騎車距離
4.HKQuantityTypeIdentifierDistanceWheelchair 輪椅距離
5. HKQuantityTypeIdentifierBasalEnergyBurned 靜息能量
6. HKQuantityTypeIdentifierActiveEnergyBurned 活動能量
7. HKQuantityTypeIdentifierFlightsClimbed 已爬樓層
8. HKQuantityTypeIdentifierNikeFuel NikeFuel
9. HKQuantityTypeIdentifierAppleExerciseTime 鍛煉分鐘數健身數據
10.HKQuantityTypeIdentifierDistanceSwimming 游泳距離
11.HKQuantityTypeIdentifierSwimmingStrokeCount 游泳沖刺次數
*主要特征
1. HKQuantityTypeIdentifierHeartRate 心率
2. HKQuantityTypeIdentifierBodyTemperature 體溫
3. HKQuantityTypeIdentifierBasalBodyTemperature 基礎體溫
4. HKQuantityTypeIdentifierBloodPressureSystolic 收縮壓
5. HKQuantityTypeIdentifierBloodPressureDiastolic 舒張壓
6. HKQuantityTypeIdentifierRespiratoryRate 呼吸速率
*數據結果
1. HKQuantityTypeIdentifierOxygenSaturation 血氧飽和度
2. HKQuantityTypeIdentifierPeripheralPerfusionIndex 末梢灌注指數
3. HKQuantityTypeIdentifierBloodGlucose 血糖
4. HKQuantityTypeIdentifierNumberOfTimesFallen 摔倒次數
5. HKQuantityTypeIdentifierElectrodermalActivity 皮電活動
6. HKQuantityTypeIdentifierInhalerUsage 吸入劑用量
7. HKQuantityTypeIdentifierBloodAlcoholContent 血液酒精濃度
8. HKQuantityTypeIdentifierForcedVitalCapacity 最大肺活量|用力肺活量
9. HKQuantityTypeIdentifierForcedExpiratoryVolume1 第一秒用力呼氣量
10.HKQuantityTypeIdentifierPeakExpiratoryFlowRate 呼氣流量峰值
*營養攝入
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 紫外線指數
2)、類別樣本(HKCategoryType)
調用方法:
[HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
*生殖健康
1. HKCategoryTypeIdentifierSleepAnalysis 睡眠分析
2.HKCategoryTypeIdentifierAppleStandHour 站立小時
3. HKCategoryTypeIdentifierCervicalMucusQuality 宮頸粘液質量
4. HKCategoryTypeIdentifierOvulationTestResult 排卵測試結果
5. HKCategoryTypeIdentifierMenstrualFlow 月經
6. HKCategoryTypeIdentifierIntermenstrualBleeding 點滴出血
7. HKCategoryTypeIdentifierSexualActivity 性行為
8.HKCategoryTypeIdentifierMindfulSession 正念分鐘數
3)、特征樣本(HKCharacteristicType)
調用方法:
[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];
*本人信息
1. HKCharacteristicTypeIdentifierBiologicalSex 性別
2. HKCharacteristicTypeIdentifierBloodType 血型
3. HKCharacteristicTypeIdentifierDateOfBirth 出生日期
4. HKCharacteristicTypeIdentifierFitzpatrickSkinType 日光反應型皮膚類型
4)、 Correlation(HKCorrelationType)
調用方法:
[HKObjectType correlationTypeForIdentifier:HKCorrelationTypeIdentifierBloodPressure];
*樣本類型不允許share和read(枚舉)
//不允許share And read
1.HKCorrelationTypeIdentifierBloodPressure 血壓
2.HKCorrelationTypeIdentifierFood 食物
5)、Document(HKDocumentType)
調用方法:
[HKObjectType documentTypeForIdentifier:HKDocumentTypeIdentifierCDA];
1.HKDocumentTypeIdentifierCDA 健康記錄請求
6). Workout(HKWorkoutType)
調用方法:
[HKObjectType workoutType];
7). activitySummaryType(健身記錄)獲取
調用方法:
[HKObjectType activitySummaryType];
5、使用
訪問數據:
HKQuantityType * quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; //設置訪問步數
HKHealthStore *healthStore = [[HKHealthStore alloc] init];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nil endDate:nil options:HKQueryOptionStrictStartDate];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if(!error && results) {
for(HKQuantitySample *samples in results) {
NSLog(@"stepCount = %@ startDate = %@ endDate=%@" , samples.quantity , samples.startDate,samples.endDate);
}
}
}];
[healthStore executeQuery:sampleQuery];
寫入數據:
HKUnit *unit = [HKUnit countUnit];
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantity *quantity = [HKQuantity quantityWithUnit:unit doubleValue:number];
HKQuantitySample *quantitySample = [HKQuantitySample quantitySampleWithType:quantityType quantity:quantity startDate:startDate endDate:endDate];
HKHealthStore *healthStore = [[HKHealthStore alloc] init];
[healthStore saveObject:quantitySample withCompletion:^(bool success, NSError *error){
block(success, error);
}];
具體的做法與封裝我已經放入git上,如果有需要可以下載看看,git項目地址:https://github.com/zhangyqyx/HealthKit
最近手機更新了ios12和Xcode10 出現了個奇特的bug ,授權的時候老是閃退,并一直提醒
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSHealthShareUsageDescription must be set in the app's Info.plist in order to request read authorization for the following types: HKQuantityTypeIdentifierStepCount'
試試問題萬能解決大法---重啟Xcode,依然無果
那用排除法,老代碼新問題,找了個ios11的機器跑了代碼試了下,果然沒問題.
一邊自己試驗各種辦法,一邊baidu,google找方法,結果大多都是老的帖子講添加權限字段在info里就好.
最后,翻到jinrui_w簡書帖子將info.plist中權限描述,改為英語才好使
貌似隨便寫英語也不好使,我試過要包含visit read "health"才好使
目前按此方法已解決,如有更好的辦法,請指正
希望大家能提出寶貴的意見,可以給我留言,也可以發郵件到我的郵箱:namezyqyx@163.com
謝謝大家,如果你有更好的想法或文章請告知,不勝感激。
參考文章:
HealthKit框架參考:http://www.cocoachina.com/ios/20140915/9624.html
HealthKit開發教程Swift版:http://www.cocoachina.com/swift/20150122/10998.html
The HealthKit Framework:https://developer.apple.com/reference/healthkit#//apple_ref/doc/uid/TP40014707