Search code examples
swiftapple-watchhealthkitwatchos

WatchOS get info from Activity app


I was wondering if there's a way to get all the data from the Activity app : get the calories burnt, distance, exercice time, etc... I managed to get the steps using this function but i cannot get the other info, anyone could help ?

func recentSteps(completion: @escaping (Double, [Double], NSError?) -> ()) {
    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)

    let date = Date()
    let calendar = Calendar.current
    let curryear = calendar.component(.year, from: date)
    let currmonth = calendar.component(.month, from: date)
    let currday = calendar.component(.day, from: date)
    let last = DateComponents(year: curryear,
                              month: currmonth,
                              day: currday)

    let dates = calendar.date(from: last)!

    let predicate = HKQuery.predicateForSamples(withStart: dates, end: Date(), options: [])
    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) {
        query, results, error in
        var steps: Double = 0
        var allSteps = [Double]()
        if let myResults = results {
            for result in myResults as! [HKQuantitySample] {
                print(myResults)
                steps += result.quantity.doubleValue(for: HKUnit.count())
                allSteps.append(result.quantity.doubleValue(for: HKUnit.count()))
            }
        }

        completion(steps, allSteps, error as NSError?)

    }

    healthStore.execute(query)
}

Solution

  • I got it to work this way, maybe this will help anyone in the future,

    for the calories burnt per day:

    func energyeUser(completion: @escaping (Double, NSError?) -> ()) {
    
        if HKHealthStore.isHealthDataAvailable() {
            let energyCount = NSSet(object: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned) as Any)
    
            let sharedObjects = NSSet(objects: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) as Any,HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) as Any)
    
            healthStore.requestAuthorization(toShare: sharedObjects as? Set<HKSampleType>, read: energyCount as? Set<HKObjectType>, completion: { (success, err) in
                self.getStepCount(sender: self)
    
            })
        }
    
        let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)
    
        let date = Date()
        let calendar = Calendar.current
        let curryear = calendar.component(.year, from: date)
        let currmonth = calendar.component(.month, from: date)
        let currday = calendar.component(.day, from: date)
        let last = DateComponents(calendar: nil,
                                  timeZone: nil,
                                  era: nil,
                                  year: curryear,
                                  month: currmonth,
                                  day: currday,
                                  hour: nil,
                                  minute: nil,
                                  second: nil,
                                  nanosecond: nil,
                                  weekday: nil,
                                  weekdayOrdinal: nil,
                                  quarter: nil,
                                  weekOfMonth: nil,
                                  weekOfYear: nil,
                                  yearForWeekOfYear: nil)
    
        let dates = calendar.date(from: last)!
    
        let predicate = HKQuery.predicateForSamples(withStart: dates, end: Date(), options: [])
        let query = HKStatisticsQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in
            var value: Double = 0
    
            if error != nil {
                print("something went wrong \(error)")
            } else if let quantity = statistics?.sumQuantity() {
                value = quantity.doubleValue(for: HKUnit.kilocalorie())
            }
    
            completion(value, error as NSError?)
    
        }
        healthStore.execute(query)
    }
    

    and called it this way:

        energyeUser() { energyU, error in
            DispatchQueue.main.sync {
                self.energyCount.setText("\(Int(energyU)) Calories Burnt")
            }
        };
    

    as for the distance:

    func distanceUser(completion: @escaping (Double, NSError?) -> ()) {
    
        if HKHealthStore.isHealthDataAvailable() {
            let distanceCount = NSSet(object: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning) as Any)
    
            let sharedObjects = NSSet(objects: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) as Any,HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) as Any)
    
            healthStore.requestAuthorization(toShare: sharedObjects as? Set<HKSampleType>, read: distanceCount as? Set<HKObjectType>, completion: { (success, err) in
                self.getStepCount(sender: self)
    
            })
        }
    
        let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)
    
        let date = Date()
        let calendar = Calendar.current
        let curryear = calendar.component(.year, from: date)
        let currmonth = calendar.component(.month, from: date)
        let currday = calendar.component(.day, from: date)
        let last = DateComponents(calendar: nil,
                                  timeZone: nil,
                                  era: nil,
                                  year: curryear,
                                  month: currmonth,
                                  day: currday,
                                  hour: nil,
                                  minute: nil,
                                  second: nil,
                                  nanosecond: nil,
                                  weekday: nil,
                                  weekdayOrdinal: nil,
                                  quarter: nil,
                                  weekOfMonth: nil,
                                  weekOfYear: nil,
                                  yearForWeekOfYear: nil)
    
        let dates = calendar.date(from: last)!
    
        let predicate = HKQuery.predicateForSamples(withStart: dates, end: Date(), options: [])
        let query = HKStatisticsQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in
            var value: Double = 0
    
            if error != nil {
                print("something went wrong")
            } else if let quantity = statistics?.sumQuantity() {
                value = quantity.doubleValue(for: HKUnit.meter())
            }
    
            completion(value, error as NSError?)
    
        }
        healthStore.execute(query)
    }