ios 健康HKSource、HKDevice、NSUUID浅谈

    //查看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];

    

    //limit1表示查询最近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];

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值