Calories not being recorded for HealthKit Watch app

别来无恙 提交于 2019-12-05 01:01:00

You can do it another way without using predicate.

weak var delegate: WorkoutSessionManagerDelegate?
let healthStore: HKHealthStore
var workoutSession: HKWorkoutSession 
var workoutStartDate: NSDate?
var workoutEndDate: NSDate?
var queries: [HKQuery] = []
var activeEnergySamples: [HKQuantitySample] = []
var distanceSamples: [HKQuantitySample] = []
var heartRateSamples: [HKQuantitySample] = []
let energyUnit = HKUnit.calorieUnit()
let distanceUnit = HKUnit.meterUnit()
let countPerMinuteUnit = HKUnit(fromString: "count/min")
var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))
let activeEnergyType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!
let heartRateType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)! // 1/3

var distanceType: HKQuantityType {
    if self.workoutSession.activityType == .Cycling {
        return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceCycling)!
    } else {
        return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!
    }
}

var currentActiveEnergyQuantity: HKQuantity
var currentDistanceQuantity: HKQuantity
var currentHeartRateSample: HKQuantitySample? 

init(context: WorkoutSessionContext) {
    self.healthStore = context.healthStore
    self.workoutSession = HKWorkoutSession(activityType: context.activityType, locationType: context.locationType)
    self.currentActiveEnergyQuantity = HKQuantity(unit: self.energyUnit, doubleValue: 0.0)
    self.currentDistanceQuantity = HKQuantity(unit: self.distanceUnit, doubleValue: 0.0)

    super.init() 
    self.workoutSession.delegate = self
}

// MARK: Active Energy Burned Streaming
func createActiveEnergyStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {

    print("Active energy query started")

    // ** Creating a match samples predicate to sum the data is no longer the convention **

    // Sum the new quantities with the current active energy quantity.
    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) else {return nil}

    // Instantiate a HKAnchoredObjectQuery object with a results handler that calls our sumEnergyBurnedSamples function
    let activeEnergyQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, samples, deletedObjects, newAnchor, error) -> Void in
        guard let newAnchor = newAnchor else {return}
        self.anchor = newAnchor
        self.addActiveEnergySamples(samples)
    }

    // Results handler that calls our addActiveEnergySamples function
    activeEnergyQuery.updateHandler = {(query, samples, deletedObjects, newAnchor, error) -> Void in
            self.anchor = newAnchor!
            self.addActiveEnergySamples(samples)
    }
    return activeEnergyQuery
}


func addActiveEnergySamples(samples: [HKSample]?) {

    print("Updating calorie samples")

    guard let activeEnergyBurnedSamples = samples as? [HKQuantitySample] else { return }

    // addActiveEnergySamples method dispatches back to the main queue
    dispatch_async(dispatch_get_main_queue()) { 

        // Adds the new active energy sample to the running total
      self.currentActiveEnergyQuantity = self.currentActiveEnergyQuantity.addQuantitiesFromSamples(activeEnergyBurnedSamples, unit: self.energyUnit)

        // Adds that sample to an array of samples accumulated over the workout
        self.activeEnergySamples += activeEnergyBurnedSamples

        // Whenever new samples become available, call the corresponding delegate method. This updates the UI with new samples.
        self.delegate?.workoutSessionManager(self, didUpdateActiveEnergyQuantity: self.currentActiveEnergyQuantity)

        // Print checks
        guard let sample = activeEnergyBurnedSamples.first else{return}
        let value = sample.quantity.doubleValueForUnit(self.energyUnit)
        print(value)
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!