4 Replies
      Latest reply on Mar 16, 2016 1:54 AM by wilmarvh
      ukaussie Level 1 Level 1 (0 points)

        I'm developing an iPhone app that retrieves data from the last recorded workout. I'm able to retrieve distance, calories, and duration no problem (lines 01-19 below). However, despite using a predicate with a start and end date (line 22), every single heart rate ever recorded is being returned rather than just those for the given workout. I guess the predicate isn't working, but I can't figure out why.


        Any suggestions?


        let predicate =  HKQuery.predicateForWorkoutsWithWorkoutActivityType(HKWorkoutActivityType.Running)
        let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
        let sampleQuery = HKSampleQuery(sampleType: HKWorkoutType.workoutType(), predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor])
             { (sampleQuery, results, error) -> Void in
                       if results == nil {
                            print("There was an error running the query: \(error)")
                       } else {
                            self.workout = results as! [HKWorkout]
                            let distance = self.workout.first?.totalDistance
                            let duration = self.workout.first?.duration
                            let energy = self.workout.first?.totalEnergyBurned
                            print("Distance: \(distance); Duration: \(duration); Energy: \(energy)")
                            self.dataLabel.text = "Distance: \(distance); Duration: \(duration); Energy: \(energy)"
        let heartRateType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
        let predicateHR = HKQuery.predicateForSamplesWithStartDate(self.workout.first?.startDate, endDate: self.workout.first?.endDate, options: HKQueryOptions.None)
        let sampleQueryHR = HKSampleQuery(sampleType: heartRateType, predicate: predicateHR, limit: 0, sortDescriptors: nil)
             { (sampleQueryHR, result, error) -> Void in
                       if result == nil {
                            print("There was an error running the query: \(error)")
                       } else {
                            for quantitySample in result! {
                                let quantity = (quantitySample as! HKQuantitySample).quantity
                                let quantityString = "\(quantity)"
                                let quantityStringNumber = quantityString.stringByReplacingOccurrencesOfString(" count/s", withString: "")
                                if let doubleVersion = Double(quantityStringNumber) {
                                    let doubleVersion60 = doubleVersion * 60
                                } else {
                                    print("String can't be converted")