我正在构建一个应用程序,该应用程序可以在手表中启动和停止锻炼会话,并且健康数据存储在HealthKit中,可以从iPhone应用程序访问该数据。在这种情况下,每当我停止然后再开始锻炼会话时,它都会打印此消息“停止的锻炼会话无法重新启动”。 但是,当我第一次启动和停止安装该应用程序时,它工作正常,并且有第二次机会显示错误消息。
override func awake(withContext context: Any?) {
super.awake(withContext: context)
processApplicationContext()
session.delegate = self
session.activate()
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func btnPress() {
if isWorkoutInProgress{
endworkoutsession()
} else {
startworkoutsession()
}
isWorkoutInProgress = !isWorkoutInProgress
}//btnpress
func createWorkoutsession(){
print("Creating a workout session!!!")
let config = HKWorkoutConfiguration()
config.activityType = .other
config.locationType = .unknown
do{
workoutsession = try HKWorkoutSession(configuration: config)
workoutsession?.delegate = self
}
catch{ print("an error occurred!!!!!!!")}
}
func startworkoutsession(){
// print("Starting Workout Session")
if workoutsession == nil {
createWorkoutsession() }
guard let session = workoutsession else {
print("Can't start a workout without a workout session.")
return
}
healthstore.start(session)
wkstartdate = Date()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(savemockrate), userInfo: nil, repeats: true)
}
func endworkoutsession(){
// print("Ending Workout session")
guard let session = workoutsession else{
print("Can't end a workout that hasn't been started.")
return
}
self.timer?.invalidate()
healthstore.end(session)
//savemockrate()
}
@objc func savemockrate(){
print("mock heart rate from workout")
let heartRateType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
let heartRateQuantity = HKQuantity(unit: HKUnit(from: "count/min"),
doubleValue: Double(arc4random_uniform(80) + 100))
let heartSample = HKQuantitySample(type: heartRateType,
quantity: heartRateQuantity, start: NSDate() as Date as Date, end: NSDate() as Date)
healthstore.save(heartSample, withCompletion: { (success, error) -> Void in
if let error = error {
print("Error saving heart sample: \(error.localizedDescription)")
}
})
}
func processApplicationContext(){
if let iPhoneContext = session.receivedApplicationContext as? [String:Bool]{
if iPhoneContext["switchStatus"] == true {
startworkoutsession()
displaylbl.setText("Switch On")
}else {
endworkoutsession()
self.timer?.invalidate()
displaylbl.setText("Switch Off")
}
}
}
}
使用Xcode 9,快速4。 我的问题是如何停下来再重新开始健身课程?