Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HealthKit Step Counter

I'm trying to use HealthKit's step counter and so far this is what I have. It doesn't fail but I don't see any activity. What am I missing?

import UIKit
import HealthKit

class ViewController: UIViewController {
    let healthStore: HKHealthStore? = {
        if HKHealthStore.isHealthDataAvailable() {
            return HKHealthStore()
        } else {
            return nil
        }
        }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let endDate = NSDate()
        let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth, value: -1, toDate: endDate, options: nil)

        let weightSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
        let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)

        let query = HKSampleQuery(sampleType: weightSampleType, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: {
            (query, results, error) in
            if results == nil {
                println("There was an error running the query: \(error)")
            }

            dispatch_async(dispatch_get_main_queue()) {
                var dailyAVG:Double = 0
                for steps in results as [HKQuantitySample]
                {
                    // add values to dailyAVG
                    dailyAVG += steps.quantity.doubleValueForUnit(HKUnit.countUnit())
                    println(dailyAVG)
                    println(steps)
                }
            }
        })


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
like image 833
Tsundoku Avatar asked Mar 02 '15 02:03

Tsundoku


People also ask

Is HealthKit the same as Apple Health?

In a nutshell, the Health app gathers information from your iPhone, Apple Watch and third-party apps to quantify data about you and your environment and display it in an easy-to-read, secure and accurate dashboard. HealthKit is the developer framework behind it that allows apps to work with Apple Health and each other.

How does Apple HealthKit work?

The Health app gathers health data from your iPhone, Apple Watch, and apps that you already use, so you can view all your progress in one convenient place. Health automatically counts your steps, walking, and running distances. And, if you have an Apple Watch, it automatically tracks your Activity data.


1 Answers

You just forgot to actually execute the query. This is all you need at the end of your viewDidLoad method:

healthStore?.executeQuery(query)

Cheers!

like image 76
Clay McIlrath Avatar answered Oct 25 '22 18:10

Clay McIlrath