我的saveWorkout()
函数是从外部ForceTouch menuItem
调用的。 menuItem
调用其本地saveSession()
函数,后者又调用外部saveWorkout()
函数。然而,当我开始一个新的锻炼会话(在Xcode中运行应用程序)时,锻炼继续我离开的地方。因此,如果我以2英里600卡的速度结束我之前的锻炼,则新锻炼从2英里600卡开始。
我最终不得不删除所有Health应用数据并再次运行应用,以便从零开始。
也许我不了解HealthKit的功能。当你saveObject
重置锻炼的地方在哪里?
P.S。当我使用真正的手表时,即使我删除所有数据/应用程序并重新开始,锻炼总是从5英里左右开始。如果我删除所有数据/应用程序,则sim从0开始。这看起来像是一个相关问题吗?
WorkoutSessionManager.swift
func saveWorkout() {
guard let startDate = self.workoutStartDate, endDate = self.workoutEndDate else {return}
let workout = HKWorkout(activityType: self.workoutSession.activityType,
startDate: startDate,
endDate: endDate,
duration: endDate.timeIntervalSinceDate(startDate),
totalEnergyBurned: self.currentActiveEnergyQuantity,
totalDistance: self.currentDistanceQuantity,
metadata: nil)
var allSamples: [HKQuantitySample] = []
allSamples += self.activeEnergySamples
allSamples += self.distanceSamples
allSamples += self.heartRateSamples
self.healthStore.saveObject(workout) { (success, error) in
if success && allSamples.count > 0 {
self.healthStore.addSamples(allSamples, toWorkout: workout, completion: { (success, error) in
print("Successful")
})
}else{
print("Failed")
}
}
}
DashboardViewController.swift
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
WorkoutSessionManager.sharedManager?.delegate = self
addMenuItemWithItemIcon(.Accept, title: "Save", action: #selector(DashboardController.saveSession))
if context is WorkoutSessionContext {
WorkoutSessionManager.sharedManager(context as! WorkoutSessionContext)
} else {
print("Fix")
}
}
func saveSession() {
WorkoutSessionManager.sharedManager!.saveWorkout()
}