iOS HealthKit 介绍

一、简介

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 {
                // 写入数据失败
            }
        }
    }

四、运行获取权限页面

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS是由苹果公司开发和发布的移动操作系统,它是iPhone、iPad和iPod Touch等设备所使用的操作系统。以下是iOS的发展历史: 2007年1月,苹果公司发布了第一代iPhone。这款手机搭载的是一个基于Mac OS X的操作系统,但它并没有被正式命名,而是被称为“iPhone OS”。 2008年6月,iPhone 3G发布,并搭载了iPhone OS 2.0。这个版本添加了App Store和对第三方应用的支持。 2009年6月,iPhone 3GS发布,并搭载了iPhone OS 3.0。这个版本添加了更多的功能,包括剪贴板、搜索、语音备忘录和通知等。 2010年4月,iPad发布,并搭载了iPhone OS 3.2。这个版本专门为iPad设计,支持更大的屏幕和更多的应用程序。 2010年6月,iPhone 4发布,并搭载了iOS 4。这个版本添加了多任务处理、FaceTime视频通话、iBooks电子书应用程序和更多的功能。 2011年10月,iPhone 4S发布,并搭载了iOS 5。这个版本添加了iCloud云服务、通知中心、iMessage消息应用程序和Siri语音助手等功能。 2012年9月,iPhone 5发布,并搭载了iOS 6。这个版本添加了苹果地图应用程序、Passbook电子票据应用程序、Facebook和Twitter集成等功能。 2013年9月,iPhone 5S和5C发布,并搭载了iOS 7。这个版本进行了全面的设计重构,添加了控制中心、AirDrop文件传输、更多的多任务处理功能等。 2014年9月,iPhone 6和6 Plus发布,并搭载了iOS 8。这个版本添加了HealthKit健康应用程序、Apple Pay移动支付、更多的键盘和语音识别功能等。 2015年9月,iPhone 6S和6S Plus发布,并搭载了iOS 9。这个版本添加了更多的多任务处理功能、更智能的Siri语音助手、更快的应用程序打开速度等。 2016年9月,iPhone 7和7 Plus发布,并搭载了iOS 10。这个版本添加了更多的3D Touch功能、iMessage应用程序商店、更丰富的通知等。 2017年9月,iPhone 8和8 Plus发布,并搭载了iOS 11。这个版本添加了ARKit增强现实应用程序、更多的iPad多任务处理功能、更快的应用程序打开速度等。 2018年9月,iPhone XS和XS Max发布,并搭载了iOS 12。这个版本添加了更快的性能、更好的增强现实功能、更好的通知管理等。 2019年9月,iPhone 11和11 Pro发布,并搭载了iOS 13。这个版本添加了黑暗模式、更好的照片编辑功能、更好的地图应用程序等。 2020年9月,iPhone 12和12 Pro发布,并搭载了iOS 14。这个版本添加了更多的小部件、应用程序库、更好的翻译应用程序等。 以上是iOS的发展历史,每一代的发布都带来了更多的功能和改进,让用户可以获得更好的体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值