天天看点

HealthKit之实战写入和删除

- (void)querystepcount

{

    if (![hkhealthstore ishealthdataavailable])

    {

        nslog(@"设备不支持healthkit"); return;

    }

    _healthstore = [[hkhealthstore alloc] init];

    hkobjecttype *type1 = [hkobjecttype categorytypeforidentifier:hkcategorytypeidentifiersleepanalysis];// 睡眠分析

    nsset *set = [nsset setwithobjects:type1, nil]; // 读集合

    hkcategorytype *stype1 = [hkcategorytype categorytypeforidentifier:hkcategorytypeidentifiersleepanalysis];

    nsset *sset = [nsset setwithobjects:stype1, nil]; // 写集合

    __weak typeof (&*self) weakself = self;

    [_healthstore requestauthorizationtosharetypes:sset readtypes:set completion:^(bool success, nserror * _nullable error) {

        if (success)

        {

            [weakself readstepcount];

        } else

            nslog(@"healthkit不允许读写");

        }

    }];

}

//查询数据

- (void)readstepcount

    // 睡眠分析

    hkcategorytype *categorytype = [hkcategorytype categorytypeforidentifier:hkcategorytypeidentifiersleepanalysis];

    hkdevice *device = [[hkdevice alloc] initwithname:@"文能设备" manufacturer:@"中国制造商" model:@"智能机" hardwareversion:@"1.0.0" firmwareversion:@"1.0.0" softwareversion:@"1.0.0" localidentifier:@"lizaochengwen" udideviceidentifier:@"wennengshebei"];

    hkcategorysample *testobject = [hkcategorysample categorysamplewithtype:categorytype value:0.25 startdate:[nsdate datewithtimeintervalsincenow:-(24 * 3600)] enddate:[nsdate date] device:device metadata:nil];

    [_healthstore saveobject:testobject withcompletion:^(bool success, nserror * _nullable error) {

        if (success) {

            nslog(@"文能设备,收集的睡眠记录保存成功");

             nslog(@"文能设备,收集的睡眠记录保存失败 %@", error);

    nsmutablearray *list= [[nsmutablearray alloc] init];

    for (float i = 1; i < 100; i++) {

        hkcategorysample *testobject = [hkcategorysample categorysamplewithtype:categorytype value:i/100.0 startdate:[nsdate datewithtimeintervalsincenow:-(24 * 3600/i)] enddate:[nsdate date] device:device metadata:nil];

        [list addobject:testobject];

    [_healthstore saveobjects:list withcompletion:^(bool success, nserror * _nullable error) {

            nslog(@"文能设备,收集的睡眠记录保存失败 %@", error);

    nsset *dset= [[nsset alloc] initwithobjects:@"文能设备", nil];

    nspredicate *catepredicate = [hkquery predicateforobjectswithdeviceproperty:hkdevicepropertykeyname allowedvalues:dset];

    [_healthstore deleteobjectsoftype:categorytype predicate:catepredicate withcompletion:^(bool success, nsuinteger deletedobjectcount, nserror * _nullable error) {

            nslog(@"文能设备,收集的睡眠记录删除成功 %@", @(deletedobjectcount));

            nslog(@"文能设备,收集的睡眠记录删除失败 %@", error);