iOS獲取健康的運(yùn)動(dòng)步數(shù)恼琼,需要注意篩選下用戶手動(dòng)編輯錄入的數(shù)據(jù)唠摹,HKMetadataKeyWasUserEntered
為1時(shí)魂务,為手動(dòng)錄入數(shù)據(jù)集币。
-
獲取健康運(yùn)動(dòng)數(shù)據(jù)前,需要在該key下添加
HealhtKit
功能
identifier添加HealthKit功能 -
在項(xiàng)目
info.plist
里添加授權(quán)描述翠忠,目前只用到了獲取步數(shù)的權(quán)限鞠苟。
獲取健康數(shù)據(jù)授權(quán)描述 開始引入
#import <HealthKit/HealthKit.h>
獲取步數(shù)問(wèn)題。
#import <HealthKit/HealthKit.h>
@interface TestGetSteps ()
@property (nonatomic, strong) HKHealthStore *hkHStore; /**< 健康數(shù)據(jù) */
@property (nonatomic, strong) HKObjectType *hkOType; /**< 獲取的權(quán)限 */
@property (nonatomic, strong) HKSampleType *hkSType; /**< 獲取采樣數(shù)據(jù)類型 */
@end
@implementation TestGetSteps
- (void)handleInitGetSteps {
if ([HKHealthStore isHealthDataAvailable]) { // 檢查是否支持獲取健康數(shù)據(jù)
self.hkHStore = [[HKHealthStore alloc] init];
self.hkOType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; //獲取步數(shù)類型
NSSet *stepSet = [NSSet setWithObject:self.hkOType];
__weak typeof(self) weakSelf = self;
[self.hkHStore requestAuthorizationToShareTypes:nil readTypes:stepSet completion:^(BOOL success, NSError * _Nullable error) { // 獲取步數(shù)授權(quán)
if (success) {
[weakSelf handleGetWalkSteps];
}else {
NSLog(@"status:%@ message:%@", @(error.code), error.domain);
}
}];
}else {
NSLog(@"message:%@", @"設(shè)備不支持HealthKit功能");
}
}
// 獲取當(dāng)天時(shí)間開始跟結(jié)束: 00:00:00 ~ 23:59:59
- (NSDate *)handleGetDateWithCaledar:(NSCalendar *)calendar nowDate:(NSDate *)nowDate hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second {
NSDateComponents *dateNowComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:nowDate];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:dateNowComponents.day];
[dateComponents setMonth:dateNowComponents.month];
[dateComponents setYear:dateNowComponents.year];
[dateComponents setHour:hour];
[dateComponents setMinute:minute];
[dateComponents setSecond:second];
return [calendar dateFromComponents:dateComponents];
}
// 獲取步數(shù)值
- (void) handleGetWalkSteps {
self.hkSType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSortDescriptor *startSortDec = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *endSortDec = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *nowDate = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
NSDate *startDate = [self handleGetDateWithCaledar:calendar nowDate:nowDate hour:0 minute:0 second:0];
NSDate *endDate = [self handleGetDateWithCaledar:calendar nowDate:nowDate hour:23 minute:59 second:59];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone]; // 篩選當(dāng)天的數(shù)據(jù)
__weak typeof(self) weakSelf = self;
HKSampleQuery *hkSQ = [[HKSampleQuery alloc] initWithSampleType:self.hkSType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[startSortDec, endSortDec] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
DEBUGLog(@"stepCounts:%@ results:%@ error:%@", query, results, error);
HKUnit *unit = [HKUnit unitFromString:@"count"];// 看返回?cái)?shù)據(jù)結(jié)構(gòu)秽之,應(yīng)該這里步數(shù)的unit可以通過(guò)count字符串來(lái)實(shí)現(xiàn)当娱。
NSInteger allSteps = 0;
for (HKQuantitySample *sampM in results) {
NSInteger isUserWrite = [sampM.metadata[HKMetadataKeyWasUserEntered] integerValue];
if (isUserWrite == 1) { // 用戶手動(dòng)錄入的數(shù)據(jù)。
}else {
double steps = [sampM.quantity doubleValueForUnit:unit];
NSInteger stepIntegrs = (NSInteger)steps;
allSteps += stepIntegrs;
}
}
NSLog(@"獲取步數(shù)成功:%ld", (long)allSteps);
}];
[self.hkHStore executeQuery:hkSQ]; // 執(zhí)行
/**
返回?cái)?shù)據(jù)格式
{
HKSample = {
HKObject = {
NSObject = {
isa = HKCumulativeQuantitySample
}
_UUID = xxx
_sourceRevision = xxx
_device = nil
_metadata = 0x000000028291c940 1 key/value pair
_provenanceID = 0
_sourceBundleIdentifier = nil
_creationTimestamp = 675566015.49851298
_contributor = nil
}
_sampleType = 0x000000028257aca0
_startTimestamp = 675565980
_endTimestamp = 675565980
}
_quantity = 0x000000028291f2e0
_freezeState = 2
_count = 1
_codableQuantitySample = nil
}
*/
}
@end