0

We are developing a health app where we need to keep track of user's accelerometer in real time. Which means we need to read accelerometer values when the screen is on and off. Is there a better way to do it other then initiating a HKWorkoutSession?

If not, what activityType should we use for HKWorkoutConfiguration?

Another question is: I noticed in some apps when you start an activity and the sensor on the back is flashing there is a thing that when you close the app by pressing the crown and turn off the screen when you turn it back on that app with activity running is presented. Like I never closed it. How do you do that? What is it connected to?

I hope that all makes sense and thank you for taking your time to read respond!

ILarsonI
  • 1
  • 1

1 Answers1

0

You don't need start a HKWorkoutSession to access to CoreMotion data like CMAccelerometerData.

Example:

import WatchKit
import Foundation
import CoreMotion

enum VelocityVector: Int {
    case x, y, z
}

class InterfaceController: WKInterfaceController {

    @IBOutlet weak var labelVelocity: WKInterfaceLabel!
    let coreMotion = CMMotionManager.init()
    let pool = OperationQueue.init()
    
    override func awake(withContext context: Any?) {
        coreMotion.accelerometerUpdateInterval = 0.1 // 0.1 seconds means frequency is 10 Hz
        coreMotion.startAccelerometerUpdates(to: pool) { data, err in
            guard let _data = data else { return }
            DispatchQueue.main.async {
                self.labelVelocity.setText(String.init(format: "G-Force (x:y:z) %.3f:%.3f:%.3f", arguments: [_data.acceleration.x, _data.acceleration.y, _data.acceleration.z]))
            }
        }
    }
    
    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
    }
    
    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
    }

}

When your watchApp start a HKWorkoutSession, it will allow watchApp process can run in the background to capture workout's live data if needed.

The sensor on the back is an HR sensor, HKWorkoutSession will force it to run until you stop HKWorkoutSession, to capture HR data during the workout.

Apps with an active workout session can run in the background, so you need to add the background modes capability to your WatchKit App Extension.

Workout sessions require the Workout processing background mode. If your app plays audio or provides haptic feedback during the workout session, you must also add the Audio background mode.

Ref: https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/running_workout_sessions

Neklas
  • 504
  • 1
  • 9