如何使用Swift访问healthkit中的锻炼元数据

时间:2016-07-19 07:37:11

标签: ios swift health-kit hksamplequery

我可以获得durationtotalEnergyBurned等活动的基本数据。 但是,如何访问HKWasUserEntered startDate

等元数据

到目前为止,这是我的代码

var predicate = HKQuery.predicateForWorkoutsWithWorkoutActivityType(HKWorkoutActivityType.Cycling)
 let sampleQuery = HKSampleQuery(sampleType: HKWorkoutType.workoutType(), predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor])
    { (sampleQuery, results, error ) -> Void in

        if let queryError = error {
            print( "There was an error while reading the samples: \(queryError.localizedDescription)")
        }
        else
        {
            print(results!)
          for samples: HKSample in results! {
                var workout: HKWorkout = (samples as! HKWorkout)
                print("workout Distance is \(workout.totalDistance)")
                print("workout Energy Burned is \(workout.totalEnergyBurned)")
                print("workout Duration in seconds is \(workout.duration)")

            }
        }
        completion(results,error)
    }

    executeQuery(sampleQuery)

当我打印results时,我得到了这个回报

  

[(46)"健康" (9.3.2)元数据:{       HKWasUserEntered = 1;   2016-07-18 10:58:00 +0500 2016-07-18 11:58:00 +0500]

所以我基本上如何从此获取HKWasUserEntered和日期?

3 个答案:

答案 0 :(得分:3)

尝试以下方法:

print("was user entered --> \(workout.metadata?[HKMetadataKeyWasUserEntered])")

答案 1 :(得分:1)

metadata上有一个HKSample字典属性。您可以打印这样的值,例如:

print("workout was user entered \(workout.metadata[HKWasUserEntered])")

答案 2 :(得分:0)

我了解元数据的工作方式。

            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)
                    }
                }