iOS HealthKit 介绍

news/2024/7/20 22:00:47 标签: ios

文章目录

  • 一、简介
  • 二、权限配置
    • 1. 在开发者账号中勾选HealthKit
    • 2. 在targets的capabilities中添加HealthKit。
    • 3. infoPlist需要配置权限
  • 三、创建健康数据管理类
    • 1. 引入头文件
    • 2. 健康数据读写权限
    • 3. 检查权限
    • 4. 读取步数数据
    • 5. 写入健康数据
  • 四、运行获取权限页面

一、简介

HealthKit是一款用于搜集和办理医疗和健康相关数据的开发工具包,它为开发者供给了拜访用户健康数据的API和框架,并使得这些数据能够与iOS设备上的其他应用程序相互共享。

HealthKit允许应用程序搜集和办理各种类型的健康数据,包含身体丈量数据(如体重、身高和心率)、健身数据(如步数和距离)、饮食数据、睡觉数据和心理健康数据等。这些数据能够从多个来历搜集,如从硬件设备(如智能手表、智能手机和健身跟踪器)中获取,或由用户手动输入。

二、权限配置

1. 在开发者账号中勾选HealthKit

在这里插入图片描述

2. 在targets的capabilities中添加HealthKit。

在这里插入图片描述

3. infoPlist需要配置权限

Privacy - Health Share Usage Description
需要您的同意,才能访问健康更新,给您带来更好的服务
Privacy - Health Update Usage Description
需要您的同意,才能分享健康数据,给您带来更好的服务
在这里插入图片描述

注意:iOS13 这里描述太粗糙,会导致程序崩溃。

三、创建健康数据管理类

1. 引入头文件

import HealthKit

2. 健康数据读写权限

// 写权限
    private func dataTypesToWrite() -> Set<HKSampleType> {
        // 步数
        let stepCountType = HKObjectType.quantityType(forIdentifier: .stepCount)
        // 身高
        let heightType = HKObjectType.quantityType(forIdentifier: .height)
        // 体重
        let weightType = HKObjectType.quantityType(forIdentifier: .bodyMass)
        // 活动能量
        let activeEnergyType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)
        // 体温
        let temperatureType = HKObjectType.quantityType(forIdentifier: .bodyTemperature)
        // 睡眠分析
        let sleepAnalysisType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
        
        let setTypes = Set([stepCountType, heightType, weightType, activeEnergyType, temperatureType, sleepAnalysisType].compactMap { $0 })
        return setTypes
    }
    
    // 读权限
    private func dataTypesToRead() -> Set<HKObjectType> {
        // 步数
        let stepCountType = HKObjectType.quantityType(forIdentifier: .stepCount)
        // 身高
        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 distance = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
        // 活动能量
        let activeEnergyType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)
        // 睡眠分析
        let sleepAnalysisType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
        
        let setTypes = Set([stepCountType, heightType, weightType, activeEnergyType, birthdayType, sexType, distance, temperatureType, sleepAnalysisType].compactMap { $0 })
        return setTypes
    }

3. 检查权限

/// 检查是否支持获取健康数据
    public func authorizeHealthKit(_ compltion: ((_ success: Bool, _ error: Error?) -> Void)?) {
        guard HKHealthStore.isHealthDataAvailable() == true else {
            let error = NSError(domain: "不支持健康数据", code: 2, userInfo: [NSLocalizedDescriptionKey: "HealthKit is not available in th is Device"])
            if let compltion = compltion {
                compltion(false, error)
            }
            return
        }
        let writeDataTypes = dataTypesToWrite()
        let readDataTypes = dataTypesToRead()
        healthStore.requestAuthorization(toShare: writeDataTypes, read: readDataTypes) { success, error in
            if let compltion = compltion {
                compltion(success, error)
            }
        }
    }

4. 读取步数数据

/// 获取步数
    public func getStepCount(_ completion: @escaping ((_ stepValue: String?, _ error: Error?) -> Void)) {
        // 要检索的数据类型。
        guard let stepType = HKObjectType.quantityType(forIdentifier: .stepCount) else {
            let error = NSError(domain: "不支持健康数据", code: 2, userInfo: [NSLocalizedDescriptionKey: "HealthKit is not available in th is Device"])
            completion(nil, error)
            return
        }
        
        // NSSortDescriptors用来告诉healthStore怎么样将结果排序。
        let start = NSSortDescriptor.init(key: HKSampleSortIdentifierStartDate, ascending: false)
        let end = NSSortDescriptor.init(key: HKSampleSortIdentifierEndDate, ascending: false)
        /*
         @param         sampleType      要检索的数据类型。
         @param         predicate       数据应该匹配的基准。
         @param         limit           返回的最大数据条数
         @param         sortDescriptors 数据的排序描述
         @param         resultsHandler  结束后返回结果
         */
        let query = HKSampleQuery.init(sampleType: stepType, predicate: HealthKitManager.getStepPredicateForSample(), limit: HKObjectQueryNoLimit, sortDescriptors: [start, end]) { _, results, error in
            guard let results = results else {
                completion(nil, error)
                return
            }
            print("resultCount = \(results.count) result = \(results)")
            // 把结果装换成字符串类型
            var totleSteps = 0
            results.forEach({ quantitySample in
                guard let quantitySample = quantitySample as? HKQuantitySample else {
                    return
                }
                let quantity = quantitySample.quantity
                let heightUnit = HKUnit.count()
                let usersHeight = quantity.doubleValue(for: heightUnit)
                totleSteps += Int(usersHeight)
            })
            print("最新步数:\(totleSteps)")
            completion("\(totleSteps)", error)
        }
        healthStore.execute(query)
    }

5. 写入健康数据

/// 写入数据
    public func writeStep() {
        let steps = HKObjectType.quantityType(forIdentifier: .stepCount)!
        let quantity = HKQuantity(unit: HKUnit.count(), doubleValue: 1000)
        let now = Date()
        let start = now.addingTimeInterval(-3600 * 24)
        let end = now
        let sample = HKQuantitySample(type: steps, quantity: quantity, start: start, end: end)
        let healthStore = HKHealthStore()
        healthStore.save(sample) { (success, _) in
            if success {
                // 数据已写入 HealthKit
            } else {
                // 写入数据失败
            }
        }
    }

四、运行获取权限页面

在这里插入图片描述


http://www.niftyadmin.cn/n/4970706.html

相关文章

Qt(C++)计算一段程序执行经过的时间

一、前言 在许多应用程序和系统中,需要对经过的时间进行计算和记录。例如 可能想要测量某个操作的执行时间,或者记录一个过程中经过的时间以进行性能分析。在这些场景下,准确地计时是非常重要的。 Qt提供了一个功能强大的计时器类QElapsedTimer,可以方便地记录经过的时间…

基于python+pyqt实现opencv银行卡身份证等识别

效果展示 识别结果 查看处理过程 历史记录 完整演示视频&#xff1a; 无法粘贴视频........ 完整代码链接 视频和代码都已上传百度网盘&#xff0c;放在主页置顶文章

xsschallenge通关(1-10)

文章目录 level1level 2level 3level 4level 5level 6level 7level 8level9level 10 level1 这一关很简单&#xff0c;标准的xss注入&#xff0c;打开hackbar&#xff0c;输入 <script>alert(/xss/)</script>点击EXECUTE&#xff0c;通关&#xff01; level 2 这…

吉客云与金蝶云星空对接集成分页查询出库单打通分布式调出单新增

吉客云与金蝶云星空对接集成分页查询出库单打通分布式调出单新增 接通系统&#xff1a;吉客云 “吉客云”是一站式企业数字化解决方案系统&#xff0c;可实现业务、财务、办公、人事等一体化管理。相对于传统多套软件系统的集成方案&#xff0c;“吉客云”具有业务流程更流畅&a…

protobuf概览

protobuf protobuf是由谷歌推出的二进制序列化与反序列化库对象。也是著名GRPC的底层依赖&#xff0c;它独立于平台及语言的序列化与反序列化标准库。 相关网址 protobuf IDL描述protobuf 开源库grpc-知乎grpc官方示例 安装protobuf可以使用vcpkg进行简易安装依赖&#xff…

展锐A13 Camera Hal dispatch模块流程 --- 上

4月份就知道展锐A13的Camera Hal有大的变动&#xff0c;但是最近一直在做一个MTK的项目&#xff0c;没去看这个新增部分的流程。最近有时间&#xff0c;就把A13上Camera Hal新增的部分流程捋 了一下&#xff0c;过程是痛苦的&#xff0c;但是坚持一遍遍去读代码&#xff0c;在结…

1.6 服务器处理客户端请求

客户端进程向服务器进程发送一段文本&#xff08;MySQL语句&#xff09;&#xff0c;服务器进程处理后再向客户端进程发送一段文本&#xff08;处理结果&#xff09;。 从图中我们可以看出&#xff0c;服务器程序处理来自客户端的查询请求大致需要经过三个部分&#xff0c;分别…

《Python基础教程》专栏总结篇

大家好&#xff0c;我是爱编程的喵喵。双985硕士毕业&#xff0c;现担任全栈工程师一职&#xff0c;热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。…