iOS HealthKit功能

作者: 清蘂翅膀的技术 | 来源:发表于2017-05-16 12:03 被阅读15次

    1.如下图所示 在Xcode中打开HealthKit功能

    2.在需要的地方#import (这里我为了方便直接在viewController写了所有代码,我也在学习这个框架,个人感觉把获取数据权限的代码放在AppDelegate中更好)

    获取步数分为两步1.获得权限2.读取步数

    3.StoryBoard设计

    4.代码部分

    ViewController.h

    [objc]view plaincopy

    #import

    #import

    @interfaceViewController:UIViewController

    @property(nonatomic,strong)HKHealthStore*healthStore;

    @end

    ViewController.m

    [objc]view plaincopy

    #import"ViewController.h"

    @interfaceViewController()

    @property(weak,nonatomic)IBOutletUILabel*StepsLable;

    @end

    @implementationViewController

    -(void)viewDidLoad{

    [superviewDidLoad];

    self.StepsLable.layer.cornerRadius=self.StepsLable.frame.size.width/2;

    self.StepsLable.layer.borderColor=[UIColorredColor].CGColor;

    self.StepsLable.layer.borderWidth=5;

    self.StepsLable.layer.masksToBounds=YES;

    }

    #pragmamark获取权限

    -(IBAction)getAuthority:(id)sender

    {

    //查看healthKit在设备上是否可用,iPad上不支持HealthKit

    if(![HKHealthStoreisHealthDataAvailable]){

    self.StepsLable.text=@"该设备不支持HealthKit";

    }

    //创建healthStore对象

    self.healthStore=[[HKHealthStorealloc]init];

    //设置需要获取的权限这里仅设置了步数

    HKObjectType*stepType=[HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

    NSSet*healthSet=[NSSetsetWithObjects:stepType,nil];

    //从健康应用中获取权限

    [self.healthStorerequestAuthorizationToShareTypes:nilreadTypes:healthSetcompletion:^(BOOLsuccess,NSError*_Nullableerror){

    if(success){

    //获取步数后我们调用获取步数的方法

    [selfreadStepCount];

    }

    else

    {

    self.StepsLable.text=@"获取步数权限失败";

    }

    }];

    }

    #pragmamark读取步数查询数据

    -(void)readStepCount

    {

    //查询采样信息

    HKSampleType*sampleType=[HKQuantityTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

    //NSSortDescriptor来告诉healthStore怎么样将结果排序

    NSSortDescriptor*start=[NSSortDescriptorsortDescriptorWithKey:HKSampleSortIdentifierStartDateascending:NO];

    NSSortDescriptor*end=[NSSortDescriptorsortDescriptorWithKey:HKSampleSortIdentifierEndDateascending:NO];

    //获取当前时间

    NSDate*now=[NSDatedate];

    NSCalendar*calender=[NSCalendarcurrentCalendar];

    NSUIntegerunitFlags=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

    NSDateComponents*dateComponent=[calendercomponents:unitFlagsfromDate:now];

    inthour=(int)[dateComponenthour];

    intminute=(int)[dateComponentminute];

    intsecond=(int)[dateComponentsecond];

    NSDate*nowDay=[NSDatedateWithTimeIntervalSinceNow:-(hour*3600+minute*60+second)];

    //时间结果与想象中不同是因为它显示的是0区

    NSLog(@"今天%@",nowDay);

    NSDate*nextDay=[NSDatedateWithTimeIntervalSinceNow:-(hour*3600+minute*60+second)+86400];

    NSLog(@"明天%@",nextDay);

    NSPredicate*predicate=[HKQuerypredicateForSamplesWithStartDate:nowDayendDate:nextDayoptions:(HKQueryOptionNone)];

    HKSampleQuery*sampleQuery=[[HKSampleQueryalloc]initWithSampleType:sampleTypepredicate:predicatelimit:0sortDescriptors:@[start,end]resultsHandler:^(HKSampleQuery*_Nonnullquery,NSArray<__kindofHKSample*>*_Nullableresults,NSError*_Nullableerror){

    //设置一个int型变量来作为步数统计

    intallStepCount=0;

    for(inti=0;i

    //把结果转换为字符串类型

    HKQuantitySample*result=results[i];

    HKQuantity*quantity=result.quantity;

    NSMutableString*stepCount=(NSMutableString*)quantity;

    NSString*stepStr=[NSStringstringWithFormat:@"%@",stepCount];

    //获取51count此类字符串前面的数字

    NSString*str=[stepStrcomponentsSeparatedByString:@""][0];

    intstepNum=[strintValue];

    NSLog(@"%d",stepNum);

    //把一天中所有时间段中的步数加到一起

    allStepCount=allStepCount+stepNum;

    }

    //查询要放在多线程中进行,如果要对UI进行刷新,要回到主线程

    [[NSOperationQueuemainQueue]addOperationWithBlock:^{

    self.StepsLable.text=[NSStringstringWithFormat:@"%d",allStepCount];

    }];

    }];

    //执行查询

    [self.healthStoreexecuteQuery:sampleQuery];

    }

    -(void)didReceiveMemoryWarning{

    [superdidReceiveMemoryWarning];

    //Disposeofanyresourcesthatcanberecreated.

    }

    @end

    5.完成效果

    点击按钮之后,首先获取获得步数权限··

    相关文章

      网友评论

        本文标题:iOS HealthKit功能

        本文链接:https://www.haomeiwen.com/subject/evhlxxtx.html