//查看healthKit在设备上是否可用,ipad不支持HealthKit
if(![HKHealthStoreisHealthDataAvailable])
{
NSLog(@"设备不支持healthKit");
}
//创建healthStore实例对象
self.healthStore = [[HKHealthStorealloc] init];
//设置需要获取的权限这里仅设置了步数
HKObjectType *stepCount = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healthSet = [NSSetsetWithObjects:stepCount, nil];
//从健康应用中获取权限
[self.healthStorerequestAuthorizationToShareTypes:nilreadTypes:healthSet completion:^(BOOL success,NSError * _Nullable error) {
if (success)
{
NSLog(@"获取步数权限成功");
[selfstartNSTimer];//开启定时器
}
else
{
NSLog(@"获取步数权限失败");
}
}];
-(void)startNSTimer{
dispatch_async(dispatch_get_main_queue(), ^{
//每秒钟取一次,更新总步数
self.totalStepsTimer = [NSTimerscheduledTimerWithTimeInterval:1target:self
selector:@selector(getTodayTotalSteps:)userInfo:nilrepeats:YES];
});
}
//每秒钟查询一次
-(void)getTodayTotalSteps:(NSTimer *)timer{
NSDate* nowDate = [NSDatedate];
NSUserDefaults *userDefault = [NSUserDefaultsstandardUserDefaults];
NSDate* launchDate = [userDefaultobjectForKey:@"firstLaunchOfToday"];
HKSampleType *sampleType = [HKQuantityTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
//predicate 使…基于 startDate比 endDate时间更为过去
NSPredicate *predicate = [HKQuerypredicateForSamplesWithStartDate:launchDateendDate:nowDate options:HKQueryOptionNone];
// NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
// HKSource *source = [HKSource defaultSource];
// //source.name是只读的属性 不能赋值 @"张雷的 iPhone";
// NSPredicate *predicate = [HKQuery predicateForObjectsFromSource:source];
// HKDevice * source = [HKDevice localDevice];
// NSLog(@"source.name: %@ source.model: %@",source.name,source.model);//iPhone iPhone
// NSSet<HKDevice *> * devices = [NSSet setWithObject:source];
// NSPredicate *predicate = [HKQuery predicateForObjectsFromDevices:devices];
// NSUUID * source = [NSUUID UUID];
// NSLog(@"source.UUIDString: %@",source.UUIDString);//8494FA8E-D68E-41F0-A07E-EC5913E1AE7B一直在变
// NSSet<NSUUID *> * UUIDs = [NSSet setWithObject:source];
// NSPredicate *predicate = [HKQuery predicateForObjectsWithUUIDs:UUIDs];
//limit给1表示查询最近1条的数据 sort将…排序
HKSampleQuery *query = [[HKSampleQueryalloc] initWithSampleType:sampleTypepredicate:predicate limit:HKObjectQueryNoLimitsortDescriptors:nilresultsHandler:^(HKSampleQuery *query,NSArray *results, NSError *error) {
if (!results) {
NSLog(@"An error occured fetching the user's tracked food. In your app, try to handle this gracefully. The error was: %@.", error);
//abort();
}
dispatch_async(dispatch_get_main_queue(), ^{
//打印查询结果
NSLog(@"resultCount = %luld result = %@",(unsignedlong)results.count,results);
if (results.count >0) {
int step =0;
int stepWatch =0;
for (HKQuantitySample *resultin results) {
HKQuantity *quantity = result.quantity;
NSLog(@"数据来源修订:%@",result.sourceRevision);
NSNumber *str = [quantityvalueForKey:@"value"];
int unitStep = [strintValue];
HKDevice* device = result.device;
NSLog(@"device:%@",device);
NSString* string = [device.hardwareVersionsubstringToIndex:6];
if ([device.nameisEqualToString:@"Apple Watch"]) {
stepWatch+=unitStep;
NSLog(@"Watch UUID:%@",result.UUID);
} elseif([string isEqualToString:@"iPhone"]) {
NSLog(@"iPhone UUID:%@",result.UUID);
step+=unitStep;
}
}
NSLog(@"手表总步数:%d 苹果总步数:%d",stepWatch,step);
self.totalStepsLabel.text = [NSStringstringWithFormat:@"总步数:%d",step];
}
});
}];
[self.healthStoreexecuteQuery:query];
}