微信和QQ的每日步数最近十分火爆,我就想为本身写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,本身动手丰衣足食。html
统计步数信息并不须要咱们本身去实现,iOS自带的健康app已经为咱们统计好了步数数据ios
咱们只要使用HealthKit框架从健康app中获取这个数据信息就能够了git
这篇文章对HealthKit框架进行了简单的介绍:http://www.cocoachina.com/ios/20140915/9624.htmlgithub
对HealthKit框架有了简单的了解后咱们就能够开始了微信
1.以下图所示 在Xcode中打开HealthKit功能多线程
2.在须要的地方#import <HealthKit/HealthKit.h>(这里我为了方便直接在viewController写了全部代码,我也在学习这个框架,我的感受把获取数据权限的代码放在AppDelegate中更好)app
获取步数分为两步1.得到权限 2.读取步数 框架
3.代码部分学习
1
2
3
4
5
|
@interface
ViewController ()
@property
(
nonatomic
, strong) HKHealthStore *healthStore;
@end
|
在- (void)viewDidLoad中获取权限atom
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
- (
void
)viewDidLoad {
[
super
viewDidLoad];
//查看healthKit在设备上是否可用,ipad不支持HealthKit
if
(![HKHealthStore isHealthDataAvailable])
{
NSLog
(@
"设备不支持healthKit"
);
}
//建立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) {
if
(success)
{
NSLog
(@
"获取步数权限成功"
);
//获取步数后咱们调用获取步数的方法
[
self
readStepCount];
}
else
{
NSLog
(@
"获取步数权限失败"
);
}
}];
}
|
读取步数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
//查询数据
- (
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的参数值就能够了
*/
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:
nil
limit:1 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query,
NSArray
<__kindof HKSample *> * _Nullable results,
NSError
* _Nullable error) {
//打印查询结果
NSLog
(@
"resultCount = %ld result = %@"
,results.count,results);
//把结果装换成字符串类型
HKQuantitySample *result = results[0];
HKQuantity *quantity = result.quantity;
NSString
*stepStr = (
NSString
*)quantity;
[[
NSOperationQueue
mainQueue] addOperationWithBlock:^{
//查询是在多线程中进行的,若是要对UI进行刷新,要回到主线程中
NSLog
(@
"最新步数:%@"
,stepStr);
}];
}];
//执行查询
[
self
.healthStore executeQuery:sampleQuery];
}
|
4.如今,咱们就已经可以从健康app中读取步数信息了
5.附上一个简单的小demo: https://github.com/wl356485255/ReadStepCount (注意更改Bundle ID,而且使用真机进行调试)
6.我如今也在学习HealthKit框架对这个框架仍是比较陌生的,上面只实现了简单的获取步数信息(其余信息也能够经过相同方式获取),代码中有不足的地方但愿可以指出。