需求:
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.