title: Healthkit not returning latest data on iphone. Using healthkit between iPhone and Apple watch
body: <p>I am creating an app that provides workout information. On apple watch i have three labels that actively shows HEARTRATE ,DISTANCE TRAVELLED and CALORIES BURNED. Things work fine with apple watch, however the area where things go bad is when i try to show this data on iphone in realtime. </p>
  
  <p><strong>APPLE WATCH PART :-</strong></p>
  
  <p>I started workout on apple watch and saved it using folling code</p>
  
  <pre><code> func startWorkoutSession() {
      // Start a workout session with the configuration
      if let workoutConfiguration = configuration {
          do {
              workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
              workoutSession?.delegate = self
              workoutStartDate = Date()
  
              healthStore.start(workoutSession!)
  
          } catch {
              // ...
          }
      }
  }
  </code></pre>
  
  <p>Then i save that workout on apple watch using following code :- </p>
  
  <pre><code> func saveWorkout() {
      // Create and save a workout sample
      let configuration = workoutSession!.workoutConfiguration
      let isIndoor = (configuration.locationType == .indoor) as NSNumber
      print("locationType: \(configuration)")
  
      let workout = HKWorkout(activityType: configuration.activityType,
                              start: workoutStartDate ?? Date(),
                              end: workoutEndDate ?? Date(),
                              workoutEvents: workoutEvents,
                              totalEnergyBurned: totalEnergyBurned,
                              totalDistance: totalDistance,
                              metadata: [HKMetadataKeyIndoorWorkout:isIndoor]);
  
      healthStore.save(workout) { success, _ in
          if success {
              self.addSamples(toWorkout: workout)
          }
      }
  
      // Pass the workout to Summary Interface Controller
      // WKInterfaceController.reloadRootControllers(withNames: ["StopPauseInterfaceController"], contexts: [workout])
  
  
      if #available(watchOSApplicationExtension 4.0, *){
          // Create the route, save it, and associate it with the provided workout.
          routeBuilder?.finishRoute(with: workout, metadata: metadata) { (newRoute, error) in
  
              guard newRoute != nil else {
                  // Handle the error here...
                  return
              }
          }
      }
      else {
          // fallback to earlier versions
      }
  }
  </code></pre>
  
  <p>Then i added samples to those workouts using following code :- </p>
  
  <pre><code> func addSamples(toWorkout workout: HKWorkout) {
      // Create energy and distance samples
      let totalEnergyBurnedSample = HKQuantitySample(type: HKQuantityType.activeEnergyBurned(),
                                                     quantity: totalEnergyBurned,
                                                     start: workoutStartDate!,
                                                     end: workoutEndDate ?? Date())
  
      let totalDistanceSample = HKQuantitySample(type: HKQuantityType.distanceWalkingRunning(),
                                                 quantity: totalDistance,
                                                 start: workoutStartDate!,
                                                 end: workoutEndDate ?? Date())
  
      // Add samples to workout
      healthStore.add([totalEnergyBurnedSample, totalDistanceSample], to: workout) { (success: Bool, error: Error?) in
          if success {
              // Samples have been added
          }
      }
  }
  </code></pre>
  
  <p><strong>IPHONE PART :-</strong></p>
  
  <p>This is where things get worse. I try to access the healthkit store using HKSampleObjectQuery and It just returns static values. P.S - I am fetching healthkit store every one second for latest data using NSTimer. </p>
  
  <p>The code which is called every second is :- </p>
  
  <pre><code>func extractDataFromHealthStore(identifier : HKQuantityTypeIdentifier,completion: @escaping (String) -&gt; ()) {
  
  
      let heightType = HKSampleType.quantityType(forIdentifier:identifier)!
      let distantPastDate = Date.distantPast
      let endDate = Date()
  
      let predicate = HKQuery.predicateForSamples(withStart: distantPastDate, end: endDate, options: .strictStartDate)
  
      // Get the single most recent Value
      let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
  
  
      let query = HKSampleQuery(sampleType: heightType, predicate: predicate, limit: 1, sortDescriptors: [sortDescriptor]) { (query, results, error) in
          if let result = results?.first as? HKQuantitySample{
              print("Height =&gt; \(result.quantity)")
  
              completion("\(result.quantity)")
  
          }else{
              print("OOPS didnt get height \nResults =&gt; \(String(describing: results)), error =&gt; \(error)")
               completion("")
          }
      }
      self.healthStore.execute(query)
  }
  </code></pre>
  
  <p>Please guide Me if my whole approach is wrong, or if it is right then what is the mistake at my end.</p>