-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorkoutManager.swift
95 lines (76 loc) · 2.83 KB
/
WorkoutManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This class manages the HealthKit interactions and provides a delegate
to indicate changes in data.
*/
import Foundation
import HealthKit
import AVFoundation
import CoreAudio
//import AudioToolbox
/**
`WorkoutManagerDelegate` exists to inform delegates of swing data changes.
These updates can be used to populate the user interface.
*/
protocol WorkoutManagerDelegate: class {
func didUpdateMotion(_ manager: WorkoutManager, gravityStr: String, rotationRateStr: String, userAccelStr: String, attitudeStr: String)
}
class WorkoutManager: MotionManagerDelegate {
// MARK: Properties
let motionManager = MotionManager()
let healthStore = HKHealthStore()
weak var delegate: WorkoutManagerDelegate?
var session: HKWorkoutSession?
// MARK: Initialization
init() {
motionManager.delegate = self
}
var counter = 0.0
var timer = Timer()
var isPlaying = false
// MARK: WorkoutManager
@objc func UpdateTimer() {
counter = counter + 0.1
//timeLabel.text = String(format: "%.1f", counter)
}
func startTest() {
// If we have already started the workout, then do nothing.
// AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTimer), userInfo: nil, repeats: true)
if (session != nil) {
return
}
// Configure the workout session.
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .tennis
workoutConfiguration.locationType = .outdoor
do {
session = try HKWorkoutSession(configuration: workoutConfiguration)
} catch {
fatalError("Unable to create the workout session!")
}
// Start the workout session and device motion updates.
healthStore.start(session!)
motionManager.startUpdates()
}
func stopWorkout() {
// If we have already stopped the workout, then do nothing.
timer.invalidate();
print(counter)
if (session == nil) {
return
}
// Stop the device motion updates and workout session.
motionManager.stopUpdates()
healthStore.end(session!)
//print(counter)
// Clear the workout session.
session = nil
}
// MARK: MotionManagerDelegate
func didUpdateMotion(_ manager: MotionManager, gravityStr: String, rotationRateStr: String, userAccelStr: String, attitudeStr: String) {
delegate?.didUpdateMotion(self, gravityStr: gravityStr, rotationRateStr: rotationRateStr, userAccelStr: userAccelStr, attitudeStr: attitudeStr)
}
}