关于HealthKit的一些探索

965 阅读2分钟

说点废话

最近在玩某个捉妖这个游戏,不是人民币玩家,也不是安卓用户,所以玩起来的时候有很多限制。不能到处抓妖于是就想着自己做一个辅助工具。先是做了一个地图辅助工具,可以让自己足不出户到处抓妖。后来发现有灵石要开,于是想改一下这个游戏的运动距离,就看了一下HealthKit,改运动步数,运动距离。后来看了一下该捉妖的权限设置,它访问的是运动与健身,应该是我之前写的这个。写都写了就把它写完吧。

教程步骤

1.做最基本的准备工作,官网教程很详细,不会英语看图都会。

2.特别说明权限设置 <key>NSHealthUpdateUsageDescription</key> <string>仅在使用期间允许</string> <key>NSHealthShareUsageDescription</key> <string>仅在使用期间允许</string>

3.基本代码设置,按照官网的来

// 
if HKHealthStore.isHealthDataAvailable() {
    let healthStore = HKHealthStore()
	  let allTypes = Set([HKObjectType.workoutType(),
                    HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
                    HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
                    HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!,
                    HKObjectType.quantityType(forIdentifier: .heartRate)!])

    healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
        if !success {
            // Handle the error here.
        }
    }
}

如果写的粗糙点,直接把上边的代码往 viewDidLoad 里一扔,按说就会有下图这样权限的提示,但是 问题来了,总是崩溃,崩溃,崩溃

权限提示

遇到崩溃问题

崩溃提示信息如下:

*** 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: HKQuantityTypeIdentifierActiveEnergyBurned, HKQuantityTypeIdentifierDistanceWalkingRunning, HKWorkoutTypeIdentifier, HKQuantityTypeIdentifierDistanceCycling, HKQuantityTypeIdentifierHeartRate'

告诉我权限没设置?! 明明我早早设置了的,为嘛崩溃啊,很头疼。最终我找到了一个解决方法。。。。。。。

解决崩溃问题

解决办法把上边的代码参数稍微改了一下

// 
if HKHealthStore.isHealthDataAvailable() {
    let healthStore = HKHealthStore()
	let allTypes = Set([HKObjectType.workoutType(),
                    HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
                    HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
                    HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!,
                    HKObjectType.quantityType(forIdentifier: .heartRate)!])

    healthStore.requestAuthorization(toShare: allTypes, read: nil) { (success, error) in
        if !success {
            // Handle the error here.
        }
    }
}

只是把requestAuthorization这个方法的read参数改为了nil, 这么一来再看看那两个权限设置的key,是不是应该加一个read……..

最后可以改步数,改运动距离了

改步数(增加)

let stepsCounts = 2000
let quantityType = HKObjectType.quantityType(forIdentifier: .stepCount)!
setHealthInfor(num: stepsCounts, type: HKUnit.count(), objectType: quantityType)

改距离(增加)

let stepsCounts = 1
            
let quantityType = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!
        // 单位比较大 
setHealthInfor(num: stepsCounts, type: HKUnit.mile(), objectType: quantityType)

// 改变步数或者距离的方法

func setHealthInfor(num: Double,type: HKUnit, objectType: HKQuantityType) {
        let stepsCounts = num
        let dateFormate = DateFormatter()
        dateFormate.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let startDate = dateFormate.date(from: "2019-07-11 16:00:00")!
        
        let endDate = Date()
        let quantity = HKQuantity(unit: type, doubleValue: stepsCounts)
        
        let temperatureSample = HKQuantitySample(type: objectType, quantity: quantity, start: startDate, end: endDate, metadata: nil)
        
        self.healthStore.save(temperatureSample) { (success, error) in
            if success {
                print("成功")
            }else {
                print("失败")
            }
        }
    }