iOS計步器枪狂,HealthKit應用雜談

需求:
1.最近需要在APP當中增加記步功能碳想,提升用戶的活躍率。并且希望能夠保留用戶的健康數(shù)據(jù)川陆。
2.根據(jù)蘋果健康的數(shù)據(jù)剂习,查詢用戶最近今天的步行和運動距離。
3.用戶在頁面當中開始記步较沪,記錄用戶的步行數(shù)據(jù)鳞绕,存入本地數(shù)據(jù)庫。

前期:
1.查看計步器開發(fā)尸曼,常用的技術(shù)们何。了解到iOS當中,針對用戶運動健康數(shù)據(jù)以及計步器功能主要涉及兩個框架HealthKit控轿,CoreMotion(最低支持到iOS8.0,硬件5S及以上)冤竹。
參考:http://www.reibang.com/p/1dd6ad5b1520 (包括在應用中打開HealthKit,Info.plist增加權(quán)限)
有一點需要特別注意:當打開HealthKit過后,會在info.plist的字段Required device capabilities 當中增加healthkit茬射,這個字段的存在會在打包上傳到itunes connect的時候報錯鹦蠕,信息如下:
ERROR ITMS-90098: "This bundle is invalid. The key UIRequiredDeviceCapabilities contains value 'healthkit' which is incompatible with the MinimumOSVersion value of '7.0'."
WARNING ITMS-90109: "This bundle is invalid. The key UIRequiredDeviceCapabilities in the Info.plist may not contain values that would prevent this application from running on devices that were supported by previous versions. Refer to QA1623 for additional information: https://developer.apple.com/library/ios/#qa/qa1623/_index.html"
因為我們線上的APP 版本包含7.0系統(tǒng)以及IPAD的支持,參考stack overflow的解答躲株,刪除info.plist當中的字段即可重新打包上傳片部。

2.查閱APPLE官方文檔關于HealthKit,CoreMotion的說明。
https://developer.apple.com/documentation/healthkit (官方HealthKit說明)
https://developer.apple.com/documentation/coremotion(官方CoreMotion說明)

3.看如下的代碼處理過程(有什么使用不當?shù)臍g迎指出):
(1)框架導入:

#import <CoreMotion/CMPedometer.h>
#import <HealthKit/HealthKit.h>

(2)添加記步管理分類

@interface KKPedometerManager : NSObject
+ (instancetype)sharedManager;

//查詢Health kit 計步數(shù)據(jù)
- (BOOL)checkHealthKitStepCountDataWithDate:(NSDate *)date Completion:(void(^)(NSString *result,NSString *timeValue))completion;
//查詢Health kit 跑步+走路里程
- (BOOL)checkHealthKitMilesDataCompletion:(void(^)(NSString *result,NSString *timeValue))completion;
//計步器查詢當天的計步數(shù)據(jù)
- (void)quereSportsDataforTodayCompltion:(void(^)(NSString *stepCount,NSString *milesCount,NSError *error))completion;
//開始計步器計步
- (void)startPedometerCountWithModelData:(KKSportsModel *)model Compltion:(void(^)(NSString *stepCount,NSString *milesCount))completion;
//停止計步
- (void)stopPedomertCount;
@end

(3)實現(xiàn)數(shù)據(jù)查詢及開啟記步數(shù)據(jù)

+(instancetype)sharedManager
{
    static KKPedometerManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.healthStore  =[[HKHealthStore alloc] init];
    }
    return self;
}

- (BOOL)checkHealthKitStepCountDataWithDate:(NSDate *)date Completion:(void (^)(NSString *, NSString *))completion
{
    BOOL isSupport = [HKHealthStore isHealthDataAvailable];
    if (isSupport) {
        self.quereDate = date;
        HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
        //        HKQuantityType *energy = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        NSSet *readType = [NSSet setWithObjects:stepType, walkType,nil];
        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:readType completion:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                HKSampleType *sampletype = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
                [self requestSportSDataType:sampletype Completion:completion];
            }else{
                if (completion) {
                    completion(nil,error.localizedDescription);
                }
                [[UIApplication sharedApplication].keyWindow makeToast:@"健康數(shù)據(jù)不允許訪問霜定,請在設置-隱私-健康中打開" duration:3.0 position:@"center"];
            }
        }];
    }else{
        [[UIApplication sharedApplication].keyWindow makeToast:@"設備不支持數(shù)據(jù)" duration:2.0 position:@"center"];
    }
    return isSupport;
}

- (BOOL)checkHealthKitMilesDataCompletion:(void(^)(NSString *result,NSString *timeValue))completion
{
    BOOL isSupport = [HKHealthStore isHealthDataAvailable];
    if (isSupport) {
        HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
        //        HKQuantityType *energy = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        NSSet *readType = [NSSet setWithObjects:stepType, walkType,nil];
        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:readType completion:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                HKSampleType *sampletype = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
                [self requestSportSDataType:sampletype Completion:completion];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:@"健康數(shù)據(jù)不允許訪問档悠,請在設置-隱私-健康中打開" duration:3.0 position:@"center"];
            }
        }];
    }else{
        [[UIApplication sharedApplication].keyWindow makeToast:@"設備不支持記步數(shù)據(jù)" duration:2.0 position:@"center"];
    }
    return isSupport;
}


- (void)requestSportSDataType:(HKSampleType *)sampletype Completion:(void(^)(NSString *result,NSString *timeValue))completion
{
    //NSSortDescriptors用來告訴healthStore怎么樣將結(jié)果排序。
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    
    HKSampleQuery *sampleQuerey = [[HKSampleQuery alloc] initWithSampleType:sampletype predicate:[self predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
            if(!error && results) {
                
                NSInteger totalNumbers = 0;
                NSInteger minutes = 0;
                if ([sampletype.identifier isEqualToString:HKQuantityTypeIdentifierStepCount]) {
                    HKUnit *stepUnit = [HKUnit countUnit];
                    for(HKQuantitySample *quantitySample in results) {
                        HKQuantity *quantity = quantitySample.quantity;
                       minutes +=  [[KKDateHandleTool sharedDateHandler] dealMinuteNumbersFromStartDate:quantitySample.startDate endDate:quantitySample.endDate];
                        NSInteger usersHeight = (NSInteger)[quantity doubleValueForUnit:stepUnit];
                        totalNumbers += usersHeight;
                    }
                    NSString *totalSteps =  [NSString stringWithFormat:@"%ld",(long)totalNumbers];
                    NSString *totalMinutes =  [NSString stringWithFormat:@"%.0f",roundf(minutes/60.0)];
                    
                    if (completion) {
                        completion(totalSteps,totalMinutes);
                    }
                    
                }else if ([sampletype.identifier isEqualToString:HKQuantityTypeIdentifierDistanceWalkingRunning] ){
                    HKUnit *stepUnit = [HKUnit meterUnit];
                    
                    //記錄查詢的日期
                    NSString * quereDateString = [[KKDateHandleTool sharedDateHandler] stringFromDate:self.quereDate];
                    for(HKQuantitySample *quantitySample in results) {
                        HKQuantity *quantity = quantitySample.quantity;
                        NSInteger usersHeight = (NSInteger)[quantity doubleValueForUnit:stepUnit];
                        totalNumbers += usersHeight;
                    }
                    NSString *totalMilesMeter = [NSString stringWithFormat:@"%.2f",(totalNumbers /1000.0)];
                    if (completion) {
                        completion(totalMilesMeter,quereDateString);
                    }
                    
                }
                
            }else{
                if (completion) {
                    completion(@"",@"");
                }
            
            }
    }];
    [self.healthStore executeQuery:sampleQuerey];
}


- (NSPredicate *)predicateForSamplesToday {
    NSDate *today  = self.quereDate;
    NSDate *fromDate = [self dateWithYear:[NSDate currentYear:today] month:[NSDate currentMonth:today] day:[NSDate currentDay:today] hour:0 minute:0 second:0];
    NSDate *endDate = [self dateWithYear:[NSDate currentYear:today] month:[NSDate currentMonth:today] day:[NSDate currentDay:today] hour:23 minute:59 second:59];
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:fromDate endDate:endDate options:HKQueryOptionNone];
    return predicate;
}

- (NSDate *)dateWithYear:(NSInteger)year
                   month:(NSInteger)month
                     day:(NSInteger)day
                    hour:(NSInteger)hour
                  minute:(NSInteger)minute
                  second:(NSInteger)second{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSTimeZone *systemTimeZone = [NSTimeZone systemTimeZone];
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setCalendar:gregorian];
    [dateComps setYear:year];
    [dateComps setMonth:month];
    [dateComps setDay:day];
    [dateComps setTimeZone:systemTimeZone];
    [dateComps setHour:hour];
    [dateComps setMinute:minute];
    [dateComps setSecond:second];
    return [dateComps date];
}

- (void)quereSportsDataforTodayCompltion:(void (^)(NSString *, NSString *, NSError *))completion
{
    
    if ([CMPedometer isStepCountingAvailable]) {
        if (!self.pedometer) {
            self.pedometer = [[CMPedometer alloc] init];
        }
        NSDate *today = [NSDate date];
        NSInteger currentYear = [NSDate currentYear:today];
        NSInteger currentMonth = [NSDate currentMonth:today];
        NSInteger currentDay =  [NSDate currentDay:today];
        NSDate *fromDate =[NSDate dateWithYear:currentYear month:currentMonth day:currentDay hour:0 minute:0 second:0];
        NSDate *endDate = [NSDate dateWithYear:currentYear month:currentMonth day:currentDay hour:23 minute:59 second:59];
        //能夠查詢出來當天的步數(shù)統(tǒng)計數(shù)據(jù)
        [self.pedometer queryPedometerDataFromDate:fromDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion(nil,nil,error);
                    }
               
                });
                
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *numberOfSteps = [NSString stringWithFormat:@"%@",pedometerData.numberOfSteps];
                    NSString *distance = [NSString stringWithFormat:@"%.2f",[pedometerData.distance floatValue]/1000.0];
                    if (completion) {
                        completion(numberOfSteps,distance,nil);
                    }
                });
            }
        }];
        
    }else{
//        [[UIApplication sharedApplication].keyWindow makeToast:@"" duration:2.0 position:@"center"];
    }
}

- (void)startPedometerCountWithModelData:(KKSportsModel *)model Compltion:(void (^)(NSString *, NSString *))completion
{
    NSDate *startCountDate = [NSDate dateWithTimeIntervalSinceNow:0];
    __block CGFloat last = [model.stepCount doubleValue];
    __block CGFloat lastDistance = [model.distance doubleValue];
    
    [self.pedometer startPedometerUpdatesFromDate:startCountDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error && completion) {
                if (completion) {
                    completion(@"0",@"0");
                }
                return ;
            }
            CGFloat newStep  = [pedometerData.numberOfSteps doubleValue] + last;
            NSString *newDistance = [NSString stringWithFormat:@"%.2f",([pedometerData.distance floatValue] + lastDistance*1000)/1000.0];
            NSString *newStepCount = [NSString stringWithFormat:@"%.0f",newStep];
            if (completion) {
                completion(newStepCount,newDistance);
            }
        });
    }];
}

- (void)stopPedomertCount
{
    [self.pedometer stopPedometerUpdates];
}


其他:審核注意事項
審核出現(xiàn)了以下的被拒問題:
Guideline 4.2.1 - Design - Minimum Functionality
Your app uses the HealthKit or CareKit APIs but does not indicate integration with the Health app in your app description and clearly identify the HealthKit and CareKit functionality in your app's user interface.
Next Steps
To resolve this issue, please revise your app description to specify that your app integrates with the Health app.
查閱審核開發(fā)文檔:
https://developer.apple.com/app-store/review/guidelines/#developer-information
然后APP信息描述當中加入了以下說明:
溫馨提示:
-XXXX已接入HealthKit,可同步數(shù)據(jù)到【健康】望浩。
-持續(xù)使用跑步GPS在后臺會影響電池續(xù)航時間辖所。
Note:
Continued use of GPS running in the background can dramatically decrease battery life.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市磨德,隨后出現(xiàn)的幾起案子缘回,更是在濱河造成了極大的恐慌吆视,老刑警劉巖,帶你破解...
    沈念sama閱讀 223,126評論 6 520
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酥宴,死亡現(xiàn)場離奇詭異啦吧,居然都是意外死亡,警方通過查閱死者的電腦和手機拙寡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,421評論 3 400
  • 文/潘曉璐 我一進店門授滓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人肆糕,你說我怎么就攤上這事般堆。” “怎么了诚啃?”我有些...
    開封第一講書人閱讀 169,941評論 0 366
  • 文/不壞的土叔 我叫張陵淮摔,是天一觀的道長。 經(jīng)常有香客問我始赎,道長和橙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,294評論 1 300
  • 正文 為了忘掉前任极阅,我火速辦了婚禮胃碾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘筋搏。我一直安慰自己,他們只是感情好厕隧,可當我...
    茶點故事閱讀 69,295評論 6 398
  • 文/花漫 我一把揭開白布奔脐。 她就那樣靜靜地躺著,像睡著了一般吁讨。 火紅的嫁衣襯著肌膚如雪髓迎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,874評論 1 314
  • 那天建丧,我揣著相機與錄音排龄,去河邊找鬼。 笑死翎朱,一個胖子當著我的面吹牛橄维,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播拴曲,決...
    沈念sama閱讀 41,285評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼争舞,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了澈灼?” 一聲冷哼從身側(cè)響起竞川,我...
    開封第一講書人閱讀 40,249評論 0 277
  • 序言:老撾萬榮一對情侶失蹤店溢,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后委乌,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體床牧,經(jīng)...
    沈念sama閱讀 46,760評論 1 321
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,840評論 3 343
  • 正文 我和宋清朗相戀三年遭贸,在試婚紗的時候發(fā)現(xiàn)自己被綠了戈咳。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,973評論 1 354
  • 序言:一個原本活蹦亂跳的男人離奇死亡革砸,死狀恐怖除秀,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情算利,我是刑警寧澤册踩,帶...
    沈念sama閱讀 36,631評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站效拭,受9級特大地震影響暂吉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜缎患,卻給世界環(huán)境...
    茶點故事閱讀 42,315評論 3 336
  • 文/蒙蒙 一慕的、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧挤渔,春花似錦肮街、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,797評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至眼刃,卻和暖如春绕辖,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背擂红。 一陣腳步聲響...
    開封第一講書人閱讀 33,926評論 1 275
  • 我被黑心中介騙來泰國打工仪际, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人昵骤。 一個月前我還...
    沈念sama閱讀 49,431評論 3 379
  • 正文 我出身青樓树碱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親涉茧。 傳聞我的和親對象是個殘疾皇子赴恨,可洞房花燭夜當晚...
    茶點故事閱讀 45,982評論 2 361

推薦閱讀更多精彩內(nèi)容