从Apple Watch和iPhone向Healthkit添加数据

时间:2018-11-12 20:16:44

标签: ios swift apple-watch health-kit

目前,我正在开发一种水应用程序,它可以从iPhone和Apple Watch向healtkit发送信息。我已经成功设置了healtkit授权,并且可以将数据发送到healtkit。

当我将数据从Apple Watch发送到healtkit时,它工作正常,在图表中也可以看到我的数据条目。奇怪的是,当我从iPhone添加数据时,该图形将被iPhone数据覆盖。监视条目仍在“显示数据”中

当我从Apple Watch添加时,它不会更新图形,但条目也位于“显示数据”中。

我正在使用共享文件(HealtKitManager.swift)文件获取Healthkit授权和“ AddWater”功能。

import Foundation
import HealthKit

class HealtKitManager: NSObject {

static let sharedInstance = HealtKitManager()

private override init() {}

let healthStore  = HKHealthStore()

func authorizeHealthKit(_ completion: @escaping((_ success: Bool, _ error: Error?) -> Void)){

        let waterType = HKObjectType.quantityType(forIdentifier: .dietaryWater)!
        let allTypes = Set([waterType])

        healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
            print("Authorization \(success)")
            completion(success, error)
        }
    }

func addWater(mL :  Double){

    let quantityType = HKQuantityType.quantityType(forIdentifier: .dietaryWater)
    let quantityUnit = HKUnit(from: "mL")
    let quantityAmount = HKQuantity(unit: quantityUnit, doubleValue: mL)

    let now = Date()

    let sample = HKQuantitySample(type: quantityType!, quantity: quantityAmount, start: now, end: now)

    let correlationType = HKObjectType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.food)

    let waterCorrelationForWaterAmount = HKCorrelation(type: correlationType!, start: now, end: now, objects: [sample])

    self.healthStore.save(waterCorrelationForWaterAmount, withCompletion: { (succes, error) in

        if (error != nil) {
            NSLog("error")
        }
    })

}

}

在我的ViewController和InterfaceController中,我连接了一些按钮,以便将一个“默认”值写入healtkit:

@IBAction func addGlassAction(_ sender: Any) {

    healtKitManager.addWater(mL: 100)

}

@IBAction func add50ml() {
   healtKitManager.addWater(mL: 50)
}

为什么iPhone应用程序是“老板”?

有没有人可以帮助我正确的方向?

0 个答案:

没有答案