[Swift] 体温をHealthCareに登録する

3 min read読了の目安(約2800字

今回目指すところ

TODO: HealthKitを用いて体温を登録したい

① HealthKitが利用可能かどうかの確認

private func availableHealthKit(handler: @escaping (_ success: Bool ) -> ()){
        if HKHealthStore.isHealthDataAvailable(){
            handler(true)
        }else{
            print("HealthKit is not available")
            handler(false)
        }
    }

HKHealthStore.isHealthDataAvailable()→HealthKitが利用できるかのメソッド
Apple Developer Documentation

② HKHealthStoreの初期化

private func setupHealthKit(handler: @escaping (_ success: Bool, _ healthStore: HKHealthStore) -> ()){
        availableHealthKit { (success) in
            if success{
                //create HealthKit instance
                let healthStore: HKHealthStore = HKHealthStore()
                requestPermissionFromUser(healthStore: healthStore) { (success) in
                    if success{
                        handler(true, healthStore)
                    }
                }
            }
        }
    }

HKHealthStoreのインスタンスを初期化する。

また、requestPermissionFromUserで③で説明する関数に投げている。

③ユーザーからの許可を申請する

private func requestPermissionFromUser(healthStore: HKHealthStore, handler: @escaping (_ success: Bool) -> ()){
        // only bodyTemperature
        let allTypes = Set([HKObjectType.quantityType(forIdentifier: .bodyTemperature)!])
        
        healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
            if !success{
                // Handle error here.
                print("Can't Request Permission From User")
                handler(false)
            }else{
                handler(true)
            }
        }
    }

allTypesで許可をもらうデータを設定する

④HealthKitにデータを投げる

func uploadBodyTemperature(bodyTmp: Double, handler: @escaping (_ success: Bool) -> ()){
        setupHealthKit { (success, healthStore) in
            if success{
                let myunit: HKUnit! = HKUnit.degreeCelsius()
                let quantity: HKQuantity = HKQuantity(unit: myunit, doubleValue: bodyTmp)
                
                let hkQunatityType: HKQuantityType = HKObjectType.quantityType(forIdentifier: .bodyTemperature)!
                
                let quantitySample = HKQuantitySample(type: hkQunatityType, quantity: quantity, start: Date(), end: Date())
                
                healthStore.save(quantitySample) { (success, error) in
                    if !success{
                        handler(false)
                    }else{
                        handler(true)
                    }
                }
            }
        }
    }

最後にデータを登録します!

参考になれば幸いです!


Github (https://github.com/RyosukeKamimura)
Twitter (http://twitter.com/Ryosuke_kamimur)