Step Count always "0" using healthKit in swift

Viewed 562

I am trying to get last 7 days step count but it is always coming zero. But when I open the health app in iPhone then it is more than 3000 steps. Even I also added property Privacy - Health Share Usage Description and Privacy - Health Update Usage Description in .plist file. Here is my code

var healthScore = HKHealthStore()

override func viewDidLoad() {
    super.viewDidLoad()
    // Access Step Count
    let healthKitTypes: Set = [ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)! ]
    // Check for Authorization
    healthScore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (bool, error) in
        if (bool) {
            // Authorization Successful
            self.getSteps { (result) in
                DispatchQueue.main.async {
                    let stepCount = String(Int(result))
                    self.stepLbl.text = String(stepCount)
                }
            }
        }
    }
}

func getSteps(completion: @escaping (Double) -> Void){
    let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

    let now = Date()
    let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: -7), to: now)!
    let predicate = HKQuery.predicateForSamples(withStart: exactlySevenDaysAgo, end: now, options: .strictStartDate)

    let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
        var resultCount = 0.0

        guard let result = result else {
            print("\(String(describing: error?.localizedDescription)) ")
            completion(resultCount)
            return
        }

        if let sum = result.sumQuantity() {
            resultCount = sum.doubleValue(for: HKUnit.count())
        }

        DispatchQueue.main.async {
            completion(resultCount)
        }
    }

    healthScore.execute(query)
}

In console I checked the dates are also correct now here's the screenshotenter image description here

0 Answers
Related