I am currently working on monitoring the motions of a person using headphones a the CMHeadphoneMotionManager
. Since I want to process the motion, I need the updates to be as frequently as possible to improve the quality of the data. In addition to processing the data, I want to display it live in a chart and save the data to CoreData
in order to access them later and try other methods for processing on previously recorded data.
I created a UML diagram of my current approach:
The MotionManagerProtocol is the protocol of the class MotionManager
, which handles the CMHeadphoneMotionManager
. MotionManager.start
looks like this:
func start() {
self.manager.startDeviceMotionUpdates(to: OperationQueue.main) { motion, error in
if let motion {
let timestamp = CACurrentMediaTime()
self.timeInterval = self.oldTimestamp < 0 ? 0 : timestamp - self.oldTimestamp
self.oldTimestamp = timestamp
self.userAcceleration = motion.userAcceleration
self.rotationRate = motion.rotationRate
self.attitude = motion.attitude
}
if let error {
print(error)
}
}
}
The attributes like userAcceleration etc are just setting the value of the CurrentValueSubject so that other classes can subscribe to changes in them.
The MotionRecorder
, MotionViewModel
and SpeedCalculator
are simply subscribing to changes in the CurrentValueSubject
of the MotionManager
to be notified when new data is available.
In order to be sure, that all are using the same MotionManager
, I created a Singleton for it.
Is this structure of my code a decent approach or are there anything I can change to make it scale better and receive the new motion data as fast as possible? Since I am pretty early in the process, I can don’t really loose anything if I have to change the whole architecture of my code, so feel free to give advice in this direction as well.
Any advice and tips on what to learn in order to improve this project are very much appreciated and TIA.
PS: I am using SwiftUI as my framework of choice