How to get HKWorkout's device name tracked by Apple Watch

432 views Asked by At

I am trying to get HKWorkout samples by HKSampleQuery in Apple's HealthKit. By the way I can't get HKWorkout's device name which was tracked by Apple Watch.

I could get several HKWorkout Sample data and confirm the sourceRevision and totalDistance are available. But the only device data couldn't be confirmed. It showed it has a null value.

Is Apple missing it on that?

Here is my code to experiment this.

func getRunningWorkouts(completionHandler: @escaping (_ data:[AnyObject]?, _ response:Bool, _ error:Error?) -> Void) {
    let predicateForRunning = HKQuery.predicateForWorkouts(with: .running)
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
    let sampleType = HKWorkoutType.workoutType()

    let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: predicateForRunning, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (query, resultsArray, error) in
        if error != nil {
            print("Get an error to extract running workout: \(error)")
            return
        }
        if let samples = resultsArray as? [HKWorkout] {

            for sample in samples {
                    print(sample.device?.name)
                    completionHandler(samples, true, nil)
                }
            }
        }


    }
    healthStore.execute(sampleQuery)
}
1

There are 1 answers

0
Allan On

You should file a bug with Apple if you believe that it's a mistake that the name of the Apple Watch is missing from the sample.