api如下
HKCategoryType *sleep1 = [HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
NSSet *healthSet = [NSSet setWithObjects:sleep1,nil];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
NSLog(@"requestAuthorization success");
[self readHealthData:HKCategoryTypeIdentifierSleepAnalysis];
}else{
NSLog(@"requestAuthorization error");
}
}];
HKSampleType *sampleType = [HKCategoryType categoryTypeForIdentifier:HKQuantityTypeIdentifierType];
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:100 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
NSLog(@"健康 resultCount = %ld result = %@",results.count,results);
if (results.count!=0) {
HKCategorySample *sample = results[0];
for (HKCategorySample *sam in results) {
NSLog(@"健康 %@",@(sam.value));
NSDate *start = sam.startDate;
NSDate *end = sam.endDate;
if(sam.value == HKCategoryValueSleepAnalysisInBed){
NSLog(@"健康 卧床时间: 开始时间:%@ --- 结束时间:%@",start,end);
}
else if (sam.value == HKCategoryValueSleepAnalysisAsleepUnspecified){
NSLog(@"健康 睡眠时间: 开始时间:%@ --- 结束时间:%@",start,end);
}
else if (sam.value == 2){
NSLog(@"健康 清醒时间: 开始时间:%@ --- 结束时间:%@",start,end);
}
else if (sam.value == 3){
NSLog(@"健康 核心睡眠时间: 开始时间:%@ --- 结束时间:%@",start,end);
}
else if (sam.value == 4){
NSLog(@"健康 深度睡眠时间: 开始时间:%@ --- 结束时间:%@",start,end);
}
else if (sam.value == 5){
NSLog(@"健康 快速动眼时间: 开始时间:%@ --- 结束时间:%@",start,end);
}
}
}
}];
[self.healthStore executeQuery:sampleQuery];