iOS之HealthKit使用

来源:互联网 发布:注册淘宝店铺要多少钱 编辑:程序博客网 时间:2024/05/19 14:36


HealthKit是iOS系统一个用来分享健康和健身数据的框架,HealthKit管理从不同来源获得的数据,并根据用户的偏好设置,自动将不同来源的所有数据合并起来。应用还可以获取每个来源的原始数据,然后执行自己的数据合并。下面简单介绍下HealthKit的使用。


1、在项目TARGETS->Capabilities->HealthKit里开启HealthKit。开启后,系统自动会生成一个xxx.entitlements的文件(xxx为项目名称),在info.plist文件中Required device capabilities对应的数组里会自动添加healthkit。






2、info.plist里配置Key值为NSHealthShareUsageDescriptionNSHealthUpdateUsageDescription,对应的Value值需要我们填写描述说明。


3、import HealthKit,请求权限,获取、写入数据信息。

获取数据

 if HKHealthStore.isHealthDataAvailable() {            let heightType = HKObjectType.quantityType(forIdentifier: .height)            let weightType = HKObjectType.quantityType(forIdentifier: .bodyMass)            let temperatureType = HKObjectType.quantityType(forIdentifier: .bodyTemperature)            let activeEnergyType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)                                    let birthdayType = HKObjectType.characteristicType(forIdentifier: .dateOfBirth)            let sexType = HKObjectType.characteristicType(forIdentifier: .biologicalSex)            let stepCountType = HKObjectType.quantityType(forIdentifier: .stepCount)            let distance = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)                        let writeDataTypes : Set<HKObjectType> = [heightType!,                                                      weightType!,                                                      temperatureType!,                                                      activeEnergyType!,                                                      stepCountType!]                        let readDataTypes : Set<HKObjectType> = [heightType!,weightType!,                                                     temperatureType!,                                                     activeEnergyType!,                                                     birthdayType!,                                                     sexType!,                                                     stepCountType!,                                                     distance!]                        self.healthStore = HKHealthStore.init()            self.healthStore?.requestAuthorization(toShare: writeDataTypes as? Set<HKSampleType>,                                                   read: readDataTypes, completion: { (success, error) in                if success {
                    print("success")                    let stepType = HKObjectType.quantityType(forIdentifier: .stepCount)                    let timeSortDescriptor = NSSortDescriptor.init(key: HKSampleSortIdentifierEndDate,                                                                   ascending: false)                    let query = HKSampleQuery.init(sampleType: stepType!,                                                   predicate: self.predicateForSamplesToday(),                                                   limit: HKObjectQueryNoLimit,                                                   sortDescriptors: [timeSortDescriptor],                                                   resultsHandler: { (query, results, error) in                        if (error != nil) {
                            //查询失败                            print(error.debugDescription)                        }else{                            //数据查询成功                        }                    })                    self.healthStore?.execute(query)
self.healthStore?.execute(query) } })}


获取今天NSPredicate

func predicateForSamplesToday() -> NSPredicate{        let calendar = Calendar.current        let now = NSDate()        let componsssss :Set<Calendar.Component> = [Calendar.Component.day,Calendar.Component.month,Calendar.Component.year]        var components = calendar.dateComponents(componsssss, from: now as Date)        components.hour = 0        components.minute = 0        components.second = 0                let startDate = calendar.date(from: components)        let endDate = calendar.date(byAdding: Calendar.Component.day, value: 1, to: startDate!)        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .init(rawValue: 0))        return predicate    }

在调用requestAuthorization方法后,应用会跳转到健康App进行数据的读和写授权


授权成功后,就可以获取到健康应用中的数据了。


写入数据:(以步数为例)

写入数据方法与读取类似,都需要先获取权限,然后写入数据


 //获取数据模型    func stepCorrelation(stepNum: Double) -> HKQuantitySample{        let endDate: NSDate = NSDate()        let startDate : NSDate = NSDate.init(timeInterval: -300, since: endDate as Date)        let stepQuantityConsumed = HKQuantity.init(unit: HKUnit.count(), doubleValue: stepNum)        let stepConsumedType = HKQuantityType.quantityType(forIdentifier: .stepCount)        let strName = UIDevice.current.name        let strModel = UIDevice.current.model        let strSysVersion = UIDevice.current.systemVersion        let localeIdentifier = Locale.current.identifier        let device = HKDevice.init(name: strName, manufacturer: "Apple", model: strModel, hardwareVersion: strSysVersion, firmwareVersion: strModel, softwareVersion: strSysVersion, localIdentifier: localeIdentifier, udiDeviceIdentifier: localeIdentifier)        let stepConsumedSample = HKQuantitySample.init(type: stepConsumedType!, quantity: stepQuantityConsumed, start: startDate as Date, end: endDate as Date, device: device, metadata: nil)        return stepConsumedSample    }


//写入步数
func addStep(stepNum: Double){                let stepCorrelationItem :HKQuantitySample = self.stepCorrelation(stepNum: stepNum)        self.healthStore?.save(stepCorrelationItem, withCompletion: { (success, error) in            if success {                //写入成功处理                print("写入数据成功")            }else {                //写入失败处理                print("写入数据失败")            }        })                }

输出结果:



原创粉丝点击