欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > iOS 苹果健康-睡眠

iOS 苹果健康-睡眠

2024/10/25 19:36:51 来源:https://blog.csdn.net/levine_hhb/article/details/141427261  浏览:    关键词:iOS 苹果健康-睡眠

直接上代码吧

  • api如下

api如下

HKCategoryType *sleep1 = [HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis]; //睡眠分析
NSSet *healthSet = [NSSet setWithObjects:sleep1,nil];
//向系统的健康APP请求数据,并回调结果[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];//NSSortDescriptors用来告诉healthStore怎么样将结果排序。NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];/*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个HKSample类所以对应的查询类就是HKSampleQuery。下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了在这里我们需要定义block里面执行哪些语句*/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];

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com