This commit is contained in:
Trey t
2023-07-08 11:48:14 -05:00
parent 5ca99cf832
commit 0b477bc182
5 changed files with 168 additions and 121 deletions

View File

@@ -11,10 +11,18 @@ import SwiftUI
import HealthKit
class WatchMainViewModel: NSObject, ObservableObject {
static let shared = WatchMainViewModel()
var session: WCSession
@Published var watchPackageModel: WatchPackageModel?
@Published var isInWorkout = false
@Published var watchPackageModel = WatchMainViewModel.defualtPackageModle
@Published var heartValue: Int?
static var defualtPackageModle: WatchPackageModel {
WatchPackageModel(currentExerciseName: "", currentTimeLeft: -1, workoutStartDate: Date())
}
let healthStore = HKHealthStore()
var hkWorkoutSession: HKWorkoutSession?
var hkBuilder: HKLiveWorkoutBuilder?
@@ -82,27 +90,106 @@ class WatchMainViewModel: NSObject, ObservableObject {
}
}
extension WatchMainViewModel {
func initWorkout() -> Bool {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .functionalStrengthTraining
configuration.locationType = .indoor
do {
hkWorkoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
hkBuilder = hkWorkoutSession?.associatedWorkoutBuilder()
} catch {
fatalError("Unable to create the workout session!")
}
guard let hkWorkoutSession = hkWorkoutSession, let hkBuilder = hkBuilder else {
return false
}
// Setup session and builder.
hkWorkoutSession.delegate = self
hkBuilder.delegate = self
/// Set the workout builder's data source.
hkBuilder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore,
workoutConfiguration: configuration)
return true
}
func startWorkout() {
// Initialize our workout
if initWorkout() {
guard let hkWorkoutSession = hkWorkoutSession, let hkBuilder = hkBuilder else {
return
}
// Start the workout session and begin data collection
hkWorkoutSession.startActivity(with: Date())
hkBuilder.beginCollection(withStart: Date()) { (succ, error) in
if !succ {
fatalError("Error beginning collection from builder: \(String(describing: error)))")
}
}
isInWorkout = true
} else {
print("didn not init workout")
}
}
func stopWorkout(sendDetails: Bool) {
guard let hkWorkoutSession = hkWorkoutSession, let hkBuilder = hkBuilder else {
return
}
hkWorkoutSession.end()
hkBuilder.endCollection(withEnd: Date()) { (success, error) in
hkBuilder.finishWorkout { (workout, error) in
DispatchQueue.main.async() {
self.hkWorkoutSession = nil
self.hkBuilder = nil
let totalEnergy = workout?.totalEnergyBurned?.doubleValue(for: .kilocalorie()) ?? -1
let watchFinishWorkoutModel = WatchFinishWorkoutModel(totalBurnedEnergery: totalEnergy, allHeartRates: self.heartRates)
let data = try! JSONEncoder().encode(watchFinishWorkoutModel)
let watchAction = WatchActions.workoutComplete(data)
let watchActionData = try! JSONEncoder().encode(watchAction)
if sendDetails {
self.send(watchActionData)
}
self.heartRates.removeAll()
self.isInWorkout = false
}
}
}
}
}
extension WatchMainViewModel: WCSessionDelegate {
func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
if let model = try? JSONDecoder().decode(WatchPackageModel.self, from: messageData) {
if let model = try? JSONDecoder().decode(PhoneToWatchActions.self, from: messageData) {
DispatchQueue.main.async {
if model.currentTimeLeft == -100 {
self.watchPackageModel = nil
return
switch model {
case .inExercise(let data):
if self.isInWorkout == false {
self.startWorkout()
}
self.watchPackageModel = data
case .reset:
self.isInWorkout = false
self.watchPackageModel = WatchMainViewModel.defualtPackageModle
self.stopWorkout(sendDetails: false)
case .endWorkout:
self.isInWorkout = false
self.watchPackageModel = WatchMainViewModel.defualtPackageModle
self.stopWorkout(sendDetails: true)
}
if self.watchPackageModel?.workoutEndDate != nil {
self.watchPackageModel = nil
self.stopWorkout()
} else if self.watchPackageModel == nil {
self.startWorkout()
}
self.watchPackageModel = model
}
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("activation did complete")
}
func send(_ data: Data) {
@@ -126,70 +213,6 @@ extension WatchMainViewModel: WCSessionDelegate {
}
extension WatchMainViewModel: HKWorkoutSessionDelegate, HKLiveWorkoutBuilderDelegate {
func initWorkout() {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .functionalStrengthTraining
configuration.locationType = .indoor
do {
hkWorkoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
hkBuilder = hkWorkoutSession?.associatedWorkoutBuilder()
} catch {
fatalError("Unable to create the workout session!")
}
guard let hkWorkoutSession = hkWorkoutSession, let hkBuilder = hkBuilder else {
return
}
// Setup session and builder.
hkWorkoutSession.delegate = self
hkBuilder.delegate = self
/// Set the workout builder's data source.
hkBuilder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore,
workoutConfiguration: configuration)
}
func startWorkout() {
// Initialize our workout
initWorkout()
guard let hkWorkoutSession = hkWorkoutSession, let hkBuilder = hkBuilder else {
return
}
// Start the workout session and begin data collection
hkWorkoutSession.startActivity(with: Date())
hkBuilder.beginCollection(withStart: Date()) { (succ, error) in
if !succ {
fatalError("Error beginning collection from builder: \(String(describing: error)))")
}
}
}
func stopWorkout() {
guard let hkWorkoutSession = hkWorkoutSession, let hkBuilder = hkBuilder else {
return
}
hkWorkoutSession.end()
hkBuilder.endCollection(withEnd: Date()) { (success, error) in
hkBuilder.finishWorkout { (workout, error) in
DispatchQueue.main.async() {
self.hkWorkoutSession = nil
self.hkBuilder = nil
let totalEnergy = workout?.totalEnergyBurned?.doubleValue(for: .kilocalorie()) ?? -1
let watchFinishWorkoutModel = WatchFinishWorkoutModel(totalBurnedEnergery: totalEnergy, allHeartRates: self.heartRates)
let data = try! JSONEncoder().encode(watchFinishWorkoutModel)
let watchAction = WatchActions.workoutComplete(data)
let watchActionData = try! JSONEncoder().encode(watchAction)
self.send(watchActionData)
self.heartRates.removeAll()
}
}
}
}
func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
print("[workoutSession] Changed State: \(toState.rawValue)")
}