The user needs to be able to stop and restart collecting motion events. Add the following method to MeasurementViewController:
| func stopMotionUpdates() { |
| motionManager.stopDeviceMotionUpdates() |
| } |
This method stops the motion events by calling stopDeviceMotionUpdates of our motionManager. Next, replace the body of the startStop(_:) method with the highlighted lines in the following code:
| @IBAction func startStop(_ sender: UIButton) { |
» | if motionManager.isDeviceMotionActive { |
» | sender.setTitle("Start", for: .normal) |
» | stopMotionUpdates() |
» | } else { |
» | sender.setTitle("Stop", for: .normal) |
» | startMotionUpdates() |
» | } |
| } |
If the motionManager is collecting data at the moment, the value isDeviceMotionActive is true. In this case we set the title of the Start/Stop button to Start, and we call a method that stops the motion events. If the device motion is not active, we set the title of the button to Stop and start the motion events.
When restarting the collection of motion events, we should delete the old data. Add the highlighted line right before the call startDeviceMotionUpdates(using:to:withHandler:) in startMotionUpdates:
| func startMotionUpdates() { |
| |
| motionManager.deviceMotionUpdateInterval = 1 / 60 |
| |
» | xAccelerationData = [] |
| |
| motionManager.startDeviceMotionUpdates( |
| using: .xArbitraryZVertical, |
| to: OperationQueue()) { motion, error in |
| |
| guard let motion = motion else { |
| return |
| } |
| let acceleration = motion.userAcceleration |
| let timestamp = motion.timestamp |
| let xData = AccelerationData(timestamp: timestamp, |
| value: acceleration.x) |
| |
| DispatchQueue.main.async { |
| self.xAccelerationData.append(xData) |
| } |
| } |
| } |
With this line we remove all collected motion events from the array. Build and run the app on your iPhone and check if you can now start and stop motion events.