Reputation: 79
I wrote this function to get the degree Celsius value during a workout. How can I get the workout name/ heartbeat etc.?
func getWorkoutWeather(workout: HKWorkout) -> Double {
if let metadata = workout.metadata {
if let mataTemperature = metadata[HKMetadataKeyWeatherTemperature] {
if let quantityTemperature = mataTemperature as? HKQuantity {
let celsius = quantityTemperature.doubleValue(for: HKUnit.degreeCelsius())
print(celsius)
return celsius
}
}
}
Upvotes: 2
Views: 1520
Reputation: 773
We need to create a separate query for each data type associated with the workout. For example, to get the full details of the workout created earlier, we would need separate queries for distance, energy burned, and heart rate etc.
Query to get the Heart rate
.
class func loadheartRateWorkouts(completion:
@escaping ([HKWorkout]?, Error?) -> Void) {
guard let heartRateType =
HKObjectType.quantityType(forIdentifier:
HKQuantityTypeIdentifier.heartRate) else {
fatalError("*** Unable to create a Heart rate type ***")
}
// Get all workouts that only came from this app.
let workoutPredicate = HKQuery.predicateForObjects(from: .default())
let startDateSort = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
let query = HKSampleQuery(sampleType: heartRateType,
predicate: workoutPredicate,
limit: 0,
sortDescriptors: [startDateSort]) { (sampleQuery, results, error) -> Void in
guard let heartRateSamples = results as? [HKQuantitySample] else {
// Perform proper error handling here.
return
}
// Use the workout's Heart rate samples here.
}
HKHealthStore().execute(query)
}
Reference: Fetching samples from the Workout
Upvotes: 1