目录

1、配置工程

2、设置Capabilities

3、设置 Info.plist

4、错误解决

5、代码编写

6、demo下载


1、配置工程

注意:Team这个地方必须是企业的或者是公司的,不能是Personal Team。如下图

2、设置Capabilities

设置完了之后,左侧会出现 XZHealthDemo.entitlements。如下图:

3、设置 Info.plist

注意:描述语句只能写 "some string value stating the reason",其他的都会崩溃。

Privacy - Health Share Usage Description  // 读取权限
some string value stating the reason
Privacy - Health Update Usage Description // 写入权限
some string value stating the reason或者
<key>NSHealthShareUsageDescription</key>
<string>some string value stating the reason</string>
<key>NSHealthUpdateUsageDescription</key>
<string>some string value stating the reason</string>

4、错误解决

出现错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSHealthUpdateUsageDescription must be set in the app's Info.plist in order to request write authorization for the following types: HKQuantityTypeIdentifierStepCount'

解决 同 3 设置Info.plist

5、代码编写

1>判断设备是否支持 HealthKit 框架

func isHealthDataAvailable() -> Bool

2>判断是否支持健康记录,iOS 12.0 以上系统

func supportsHealthRecords() -> Bool

3>某一种健康类型的支持状态

func authorizationStatus(for type: HKObjectType) -> HKAuthorizationStatusHKAuthorizationStatus 有3种结果:
notDetermined // 不确定
sharingDenied  // 不允许
sharingAuthorized // 允许

4>请求读写权限:在用户读取和写入数据之前,需要请求是否有权限。

要自定义显示在授权表上的消息,请在您的应用程序中设置以下键 Info.plist 中:

设置NSHealthShareUsageDescription键,自定义用于读取数据的消息。

设置NSHealthUpdateUsageDescription键,自定义用于编写数据的消息。

func requestAuthorization(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping (Bool, Error?) -> Void)

5>是否有读写的权限,iOS 12.0 系统以上

func getRequestStatusForAuthorization(toShare typesToShare: Set<HKSampleType>, read typesToRead: Set<HKObjectType>, completion: @escaping (HKAuthorizationRequestStatus, Error?) -> Void)

6>保存某个数据

func save(_ object: HKObject, withCompletion completion: @escaping (Bool, Error?) -> Void)

7>保存多个数据

func save(_ objects: [HKObject], withCompletion completion: @escaping (Bool, Error?) -> Void)

8>执行查询方法

func execute(_ query: HKQuery)

9>停止查询

func stop(_ query: HKQuery)

导入HealthKit框架

import HealthKit

授权读写步数

    /// 授权 步数 读写func authorizeStepCount(completed: @escaping ((_ isSuccess: Bool)->Void)) {if HKHealthStore.isHealthDataAvailable() {let writeTypes = stepCountToWrite()let readTypes = stepCountToRead()healthStore.requestAuthorization(toShare: writeTypes, read: readTypes) { (success, error) incompleted(success)print("----步数读写:", success)}}}/// 步数 读 权限func stepCountToRead() -> Set<HKQuantityType>? {let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)return Set(arrayLiteral: stepType!)}/// 步数 写 权限func stepCountToWrite() -> Set<HKQuantityType>? {let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)return Set(arrayLiteral: stepType!)}

授权 读写 健康数据

 func authorizeHealthKit(completed: @escaping ((_ isSuccess: Bool)->Void)) {let version = UIDevice.current.systemVersion.floatValue()if version >= 8.0 {if !HKHealthStore.isHealthDataAvailable() {//                let error = NSError(domain: "com.xz.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in th is Device"])completed(false)}else { // 可用// 需要读写的数据类型let writeDataTypes = dateTypeToWrite()let readDataTypes = dateTypeToRead()// 注册需要读写的数据类型,也可以在'健康'中重新修改healthStore.requestAuthorization(toShare: writeDataTypes, read: readDataTypes, completion: { (isSuccess, error) inprint("错误:", error)print("权限结果:", isSuccess)completed(isSuccess)})}}else {print("iOS 系统低于8.0")completed(false)}}// 读取 Health 数据func dateTypeToRead() -> Set<HKQuantityType>? {// 身高let heightType = HKObjectType.quantityType(forIdentifier: .height)// 体重let weightType = HKObjectType.quantityType(forIdentifier: .bodyMass)// 体温let temperatureType = HKObjectType.quantityType(forIdentifier: .bodyTemperature)// 生日let birthdayType = HKObjectType.characteristicType(forIdentifier: .dateOfBirth)// 性别let sexType = HKObjectType.characteristicType(forIdentifier: .biologicalSex)// 步数let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount)// 距离let distanceType = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)// 活动能量let activeEnergyType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)return Set(arrayLiteral: heightType, temperatureType, birthdayType, sexType, weightType, stepCountType, distanceType, activeEnergyType) as? Set<HKQuantityType>}// 写 Health 数据func dateTypeToWrite() -> Set<HKQuantityType>? {// 身高let heightType = HKObjectType.quantityType(forIdentifier: .height)// 体重let weightType = HKObjectType.quantityType(forIdentifier: .bodyMass)// 体温let temperatureType = HKObjectType.quantityType(forIdentifier: .bodyTemperature)// 活动能量let activeEnergyType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)return Set(arrayLiteral: heightType, temperatureType, weightType, activeEnergyType) as? Set<HKQuantityType>}

修改数据

    func recordStepData(step: Int, completed: @escaping ((_ success: Bool)->Void)) {let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)if HKHealthStore.isHealthDataAvailable() {let stepQuantity = HKQuantity(unit: HKUnit.count(), doubleValue: Double(step))let stepSample = HKQuantitySample(type: stepType!, quantity: stepQuantity, start: Date(), end: Date())healthStore.save(stepSample) { (isSuccess, error) inprint("修改结果:", isSuccess)completed(isSuccess)}}else {print("写入不允许")}}

获取步数数据

    /// 获取步数func getStepCount(completion: @escaping ((_ value: Int)->Void)) {// 步数let stepType = HKObjectType.quantityType(forIdentifier: .stepCount)let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)let query = HKSampleQuery(sampleType: stepType!, predicate: predicateForSampelsToday(), limit: HKObjectQueryNoLimit, sortDescriptors: [timeSortDescriptor]) { (query, results, error) inif error != nil {completion(0)}else {var totalStep = 0if let results = results {for quantitySample in results {let quantitySam = quantitySample as! HKQuantitySamplelet quantity = quantitySam.quantitylet heightUnit = HKUnit.count()let usersHeight = quantity.doubleValue(for: heightUnit)totalStep += Int(usersHeight)}print("当天行走步数 =", totalStep)completion(totalStep)}}}// 执行查询healthStore.execute(query)}

6、demo下载

下一篇:《XZ_iOS 之 使用 CoreMotion 获取步数》

XZ_Swift 之HealthKit 获取手机计步统计相关推荐

  1. 浏览器js 获取手机标识信息_手机软件多次要求获取手机信息,习惯性让其通过有安全隐患?...

    大家在平常用手机新安装一个手机软件时,第一次打开该软件都会提示需要你允许该软件获取你的信息,为了方便我们一般都不会仔细去看究竟是哪一项权限,大多数的APP只是申请要麦克风或者摄像头的权限而已.但是总是 ...

  2. 微信小程序 获取 手机验证码 短信验证码 后端功能实现解析

    本文原创首发CSDN,链接 https://mp.csdn.net/console/editor/html/106041472 ,作者博客https://blog.csdn.net/qq_414641 ...

  3. android获取手机流量使用情况

    软件流量使用数据保存在 /proc/uid_stat/uid(用户id)/ 下面文件中 /proc/uid_stat/uid/tcp_send        上传流量 /proc/uid_stat/u ...

  4. 关于开发微信公众号获取手机用户运动数据的功能实现思路

    一.前沿研究 微信公众号开发文档,浏览后没有任何关于获取微信运动数据的接口 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp144 ...

  5. android 系统应用流量,android获取手机流量使用情况

    软件流量使用数据保存在/proc/uid_stat/uid(用户id)/ 下面文件中 /proc/uid_stat/uid/tcp_send        上传流量 /proc/uid_stat/ui ...

  6. ios imei android,获取手机(ios,android)的设备唯一码(mac地址, IMEI)

    获取手机(ios,android)的设备唯一码(mac地址, IMEI) app中总会用到客户端下载量数据统计,一般都是用的设备的唯一码作为标示,以下是获取mac地址的代码片段,记录备份. andro ...

  7. 获取手机通讯录 (含SIM卡中的联系人)

    sim卡UIR content://icc/fdn content://sim/fdn MOTO XT800比较异常,通讯录在: content://contacts/phones 1.使用andro ...

  8. 的s健康软件可以测试心率.,小编亲身体验 告诉你手机计步/心率准不准

    随着智能手机的发展,其功能越来越强大,不得不承认,手机已经在衣食住行等方方面面深刻地影响着我们,除此之外还渗透到学习教育.婚恋育儿.医疗健康等领域. 现代人非常重视个人健康问题,清晨或晚上的公园里,我 ...

  9. 实现用户手机流量统计(ReduceTask并行度控制)

    需求:1.实现用户手机流量统计(ReduceTask并行度控制) 数据如下:保存为.dat文件(因为以\t切分数据,文件格式必须合适) 13726230503 00-FD-07-A4-72-B8:CM ...

  10. Android如何获取手机各项信息

    本文为转载 原文地址:点击打开链接 1.使用Build获取架构属性  下面我们来根据源码看看通过Build这个类可以得到哪些配置信息,具体就不解释了,从命名基本可以理解其代表的属性. public c ...

最新文章

  1. java刷新操作_java实现删除某条信息并刷新当前页操作
  2. node-webkit教程(16)调试typescript
  3. 三. python面向对象(私有属性和私有方法 私有静态方法 私有类方法)
  4. hdu1394 Minimum Inversion Number 线段树和树状数组
  5. MaxCompute与OSS非结构化数据读写互通(及图像处理实例)
  6. IBM Cloud Paks:云端追光者也!
  7. sublime安装与使用
  8. tomcat7的安装与maven安装
  9. hc06蓝牙模块介绍_微测评 | 小米智能插座蓝牙网关版
  10. 第26条:优先考虑泛型
  11. python html表格模版,python-如何使用模板(例如Jinja2)将列值列表呈现到表中
  12. Java实现微信轰炸
  13. 花几千块钱,线上培训软件测试有用吗?
  14. linux7.5有哪些版本,CentOS Linux 7.5正式发布,基于Red Hat Enterprise Linux 7.5
  15. java计算机毕业设计BS用户小票系统(附源码、数据库)
  16. 计算机游戏本和商务本的区别,商务本和游戏本有什么区别
  17. CTF Reverse fantasy.apk解题思路
  18. Problem A: 算法4-5:求子串位置的定位函数
  19. python学习之recognition的多人人脸识别
  20. Spring的下载及目录结构

热门文章

  1. Java开发手册!java项目描述模板,挥泪整理面经
  2. 怎样添加网络扫描到计算机名,为扫描仪添加局域网功能
  3. Vba_下载网络文件(图片)
  4. Archlinux电源管理
  5. 中投 汇金 中金 中登
  6. 通过相关系数和自由度求置信度
  7. 查看IP访问服务器日志的次数
  8. System Repair Engineer (SREng) 2.6 正式发布
  9. 标准粒子群算法(PSO)
  10. Win10任务栏卡死,无响应,点不动解决方法集锦