如何使用swift在我锻炼的元数据字段中添加个人数据



我是swift的新手。我有个问题找不到解决办法。

我想在训练的元数据字段中添加个人数据(motionManager类中的箭头计数(。

我应该在我的代码中添加什么才能做到这一点,好吗?

// MARK: Properties
let motionManager = MotionManager() 
let healthStore = HKHealthStore()
var builder: HKLiveWorkoutBuilder!
weak var delegate: WorkoutManagerDelegate?
var session: HKWorkoutSession?
// MARK: WorkoutManager
func startWorkout() {
let typesToShare: Set = [ HKQuantityType.workoutType()  ]
let typesToRead: Set = [  HKQuantityType.quantityType(forIdentifier: .heartRate)!   ]
healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { (succ, error) in
if !succ { }
}
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .archery
workoutConfiguration.locationType = .unknown
do {
session = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
builder = session?.associatedWorkoutBuilder()
} catch {
}
builder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: workoutConfiguration)
session?.startActivity(with: Date())
builder.beginCollection(withStart: Date()) { (succ, error) in
if !succ { }
}    
motionManager.startUpdates()
}
func stopWorkout() {
if (session == nil) {  return   }
motionManager.stopUpdates()        
print("****** END ****** ARROWS COU%NT : (motionManager.arrowsCount)")

let quantity = HKQuantity.init(unit: HKUnit.count(), doubleValue: Double(motionManager.arrowsCount))
//      WHAT SHOULD I DO TO SAVE QUANTITY IN METADATA OF THE WORKOUT ?
session?.end()
builder.endCollection(withEnd: Date()) { (success, error) in
self.builder.finishWorkout { (workout, error) in
DispatchQueue.main.async() {
self.session = nil
self.builder = nil
}
}
}
session = nil
}

您的构建器有一个addMetadata函数。称之为通过[String: Any]

builder.addMetadata(["YourKey": quantity])

最新更新