iOS开发 获取系统HealthKit的步数

iOS10之后需要在info.plist添加权限,以便访问HealthKit;

关于HealthKit获取步数,我写了一个类,以方便使用;

//  Created by 小广 on 2016/10/31.
//  Copyright © 2016年 All. All rights reserved.
//  健康数据的帮助类

#import <Foundation/Foundation.h>

typedef void(^SCHealthBlock)(BOOL success, NSString *stepCount);

@interface SCHealthHelper : NSObject

// 开启健康数据中心
- (void)setupHKHealthStore:(SCHealthBlock)block;

@end


//
//  SCHealthHelper.m
//  SuperCommunity
//
//  Created by 小广 on 2016/10/31.
//  Copyright © 2016年 All. All rights reserved.
//  健康数据的帮助类

#import "SCHealthHelper.h"
#import <HealthKit/HealthKit.h>

@interface SCHealthHelper ()

@property (nonatomic, strong) HKHealthStore *healthStore;
@property (nonatomic, copy) SCHealthBlock block;

@end

@implementation SCHealthHelper

// 开启健康数据中心
- (void)setupHKHealthStore:(SCHealthBlock)block {
    //查看healthKit在设备上是否可用,ipad不支持HealthKit
    if(![HKHealthStore isHealthDataAvailable]) {
        SCLog(@"设备不支持healthKit");
        block(NO, nil);
        return;
    }
    
    self.block = block;
    
    //创建healthStore实例对象
    self.healthStore = [[HKHealthStore alloc] init];
    
    //设置需要获取的权限这里仅设置了步数
    HKObjectType *stepCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    NSSet *healthSet = [NSSet setWithObjects:stepCount, nil];
    
    //从健康应用中获取权限
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
        
        SCLog(@"error=error==error===%@==",error);
        if (success) {
            SCLog(@"获取步数权限成功");
            //获取步数后我们调用获取步数的方法
            [self readStepCount];
        } else {
            SCLog(@"获取步数权限失败");
        }
    }];
}

// 查询数据
- (void)readStepCount {
    //查询采样信息
    HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    //NSSortDescriptors用来告诉healthStore怎么样将结果排序。
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    
    /*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个
     HKSample类所以对应的查询类就是HKSampleQuery。
     下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了
     */
    
    @weakify(self);
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:[self predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
        
        @strongify(self);
        NSString *stepStr = @"";
        BOOL success = NO;
        if(!error && results) {
            //打印查询结果
            SCLog(@"resultCount = %ld result = %@",results.count,results);
            if (results.count > 0) {
                NSInteger totleSteps = 0;
                for(HKQuantitySample *quantitySample in results) {
                    HKQuantity *quantity = quantitySample.quantity;
                    HKUnit *heightUnit = [HKUnit countUnit];
                    NSInteger usersHeight = (NSInteger)[quantity doubleValueForUnit:heightUnit];
                    totleSteps += usersHeight;
                }
                
                //把结果装换成字符串类型
                stepStr = [NSString stringWithFormat:@"%ld",(long)totleSteps];
                success = YES;
                SCLog(@"最新步数:%@",stepStr);
            }
        }
        
        if (self.block) {
            self.block(success, stepStr);
        }
    }];
    //执行查询
    [self.healthStore executeQuery:sampleQuery];
}


/*!
 *  获取当天的时间段
 *  @brief  当天时间段
 *
 *  @return 时间段
 */
- (NSPredicate *)predicateForSamplesToday {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond: 0];
    
    NSDate *startDate = [calendar dateFromComponents:components];
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
    return predicate;
}

@end



使用的时候

[self.healthHelper setupHKHealthStore:^(BOOL success, NSString *stepCount) {
        if (!success) {
            [SVProgressHUD showErrorWithStatus:@"未获取到健康数据,请开启健康数据共享"];
        }
    }];

就是有可能没有允许读取步数,即是success为false时,来个提示框,提醒一下用户去健康开启一下;


ps:上传AppStore的时候,健康HealthKit出现了问题,info.plist文件里 Required device capabilities的healthkit导致无法上传,

 NOTE

When you enable the HealthKit capabilities, Xcode adds HealthKit to the list of required device capabilities. This prevents users from purchasing or installing the app on devices that do not support HealthKit.

If HealthKit is not required for the correct operation of your app, you can open the app’s info.plist file and delete the healthkit entry from the Required device capabilities array.

For more information on required device capabilities, see the  UIRequiredDeviceCapabilities key in Information Property List Key Reference.

当您启用HealthKit能力,Xcode增加HealthKit到所需的设备功能的列表。这样可以防止用户在购买或不支持的设备HealthKit安装该应用程序。

如果不需要为您的应用程序的正确操作HealthKit,您可以打开应用程序的Info.plist文件,并删除所需的设备功能阵列healthkit项。

有关所需的设备功能的详细信息,请参阅信息属性列表键参考的UIRequiredDeviceCapabilities关键字。
解决方案,直接将info.plist文件里healthkit这个键值对删除即可;

参考文章:http://www.cnblogs.com/luoxiaofu/p/5259320.html

参考文章:http://www.cocoachina.com/ios/20140915/9624.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值