0

I know this questions been asked, but hasn't really been answered. I've tried things from threads like this: Heart Rate With Apple's Healthkit

I tried converting this from Objective-C to Swift but didn't work.

My question is, what's the best way to read heart rate data from health kit. I want to be able to read every heart rate measurement from the time it started taking them, and I want to be able to see the time/day stamps of said measurements.

I asked for permission here:

import Foundation
import UIKit
import HealthKit

class HealthKitManager: NSObject {

static let healthKitStore = HKHealthStore()

static func authorizeHealthKit() {

    let healthKitTypes: Set = [
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
    ]

    healthKitStore.requestAuthorizationToShareTypes(healthKitTypes,
                                                    readTypes: healthKitTypes) { _, _ in }
    }
}

Here is my view Controller code for now (I'm not sure why this doesn't work):

import UIKit
import HealthKit

class ViewController: UIViewController {

let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType   = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKQuery?


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

     @IBAction func authorizeTapped(sender: AnyObject) {
    print("button tapped")
    self.createStreamingQuery()
    HealthKitManager.authorizeHealthKit()

}


func createStreamingQuery() -> HKQuery
{
    let queryPredicate  = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: .None)

    let query:HKAnchoredObjectQuery = HKAnchoredObjectQuery(type: self.heartRateType, predicate: queryPredicate, anchor: nil, limit: Int(HKObjectQueryNoLimit))
    { (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in

        if let errorFound:NSError = error
        {
            print("query error: \(errorFound.localizedDescription)")
        }
        else
        {
            //printing heart rate
            if let samples = samples as? [HKQuantitySample]
            {
                if let quantity = samples.last?.quantity
                {
                    print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
                }
            }
        }
    }

    query.updateHandler =
        { (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in

            if let errorFound:NSError = error
            {
                print("query-handler error : \(errorFound.localizedDescription)")
            }
            else
            {
                //printing heart rate
                if let samples = samples as? [HKQuantitySample]
                {
                    if let quantity = samples.last?.quantity
                    {
                        print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
                    }
                }
            }//eo-non_error
    }//eo-query-handler

    return query
}


}

I can't get anything to print to the console, which is really just what I want.

Also - none of this code is going towards homeworks, personal/professional projects...etc. Its just for fun/to learn, and most of this code is what I tried and what I've found looking through multiple stack over flow and other forums.

Community
  • 1
  • 1
dnaland
  • 1
  • 1
  • 4

1 Answers1

0

You need to actually execute your query.

let query = self.createStreamingQuery()
self.health.executeQuery(query)
Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61
  • Thank you! One more thing, now the memory address is being printed, how can I change this to readable data? – dnaland May 14 '16 at 20:14
  • @dnaland sorry, I did not understand what you were saying. Could you please clarify? – Pranav Wadhwa May 14 '16 at 20:36
  • When I try running the code this is what is printed to the console: warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available. How can I convert the into reading data? – dnaland May 14 '16 at 20:56
  • @dnaland try calling .description on whatever you are printing. – ShayanK Aug 19 '16 at 16:59