Apple Watch HKWorkoutSession does not collect the health data sometimes

I am creating a workout session but sometimes for some of the users, the health monitors do not work like the distance and the heart rate are not fetched. When the workout is finished and after that the activity is started again the health data is fetched correctly. Does anybody has any idea why is this happening and what might be the reason for this. Following is the code of starting an activity:
Code Block
/// create and begin a workout session for the activity
    func startWorkout(activityId: Int, startTime: Date, completion: @escaping (_ success: Bool, _ error: DIError?) -> Void) {
        self.activityId = activityId
        self.workoutStartTime = startTime
        guard let healthStore = HealthKitInterface.sharedInstance?.healthKitDataStore else {
            return
        }
        self.healthStore = healthStore
        self.configuration = HKWorkoutConfiguration()
        configuration.activityType = self.configActivityType()
        configuration.locationType = .outdoor
        if self.configActivityType() == .swimming {
            configuration.swimmingLocationType = .openWater
        }
        // Create the session and obtain the workout builder.
        do {
            if let activeSession = self.activeSession {
                session = activeSession
            } else {
                session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
            }
            builder = session.associatedWorkoutBuilder()
        } catch(let error) {
            //FIXME:-dismiss()
            let diError = DIError(error: error)
            completion(false, diError)
            return
        }
        // Setup session and builder.
        session.delegate = self
        setBuilderDataSourceDelegate()
        // Start the workout session and begin data collection.
        //if the session is already started, then we dont need to start activity or begin collection
//if session is not already started
        if self.activeSession == nil {
            session.startActivity(with: workoutStartTime)
            builder.beginCollection(withStart: workoutStartTime) { (success, error) in
            }
        }
    }


I believe the metrics that are enabled automatically depend on the activity type and location. At least that is the case for distance. I'm not sure what the HR issue is, assuming this is a watch workout. But maybe it's an apple health permission issue. Also, check if Power Saving mode is on. That limits heart rate monitoring. Open the watch app on your phone, tap on General and see if Workout Power Saving Mode is turned on. If so, turn it off.

Apple Watch HKWorkoutSession does not collect the health data sometimes
 
 
Q