- (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(@"文能设备,收集的睡眠记录保存成功");
} else
{
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) {
if (success) {
NSLog(@"文能设备,收集的睡眠记录保存成功");
} else
{
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) {
if (success) {
NSLog(@"文能设备,收集的睡眠记录删除成功 %@", @(deletedObjectCount));
} else
{
NSLog(@"文能设备,收集的睡眠记录删除失败 %@", error);
}
}];
}