I am trying to build an app that simply reads a user Active Energy from HealthKit and just prints out the number to the screen in a label. But weirdly instead of just printing out a single number, the output looks like the following:
I know it prints the active KiloCalories and the time the request was taken, but how would I possibly be able to
A) Strip all the unnecessary text and only print out just an integer that represents the active energy B) Have the data update live along with HealthKit C) Convert KiloCalories to Calories
I am fairly new to Swift so I am not exactly sure what to do here. I know that to convert from KiloCalories to Calories I could just mathematically calculate the results but there must be something in Swift that will do this for me automatically. Anyways, thanks for any help in advance!
I have included my code is below:
import UIKit
import HealthKit
class ViewController: UIViewController {
@IBOutlet weak var displayData: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// create store
let healthStore = HKHealthStore()
let startDate = NSDate.distantPast()
let endDate = NSDate()
// create an object type to request an authorization for a specific category, here is SleepAnalysis
if let energyType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) {
let setType = Set<HKSampleType>(arrayLiteral: energyType)
healthStore.requestAuthorizationToShareTypes(setType, readTypes: setType, completion: { (success, error) -> Void in
// here is your code
})
}
if let energyType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) {
// we create a predicate to filter our data
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,endDate: endDate ,options: .None)
// I had a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
healthStore.executeQuery(HKSampleQuery(
sampleType: energyType,
predicate: predicate,
limit: 30,
sortDescriptors: [sortDescriptor],
resultsHandler: { (query: HKSampleQuery?, results: [HKSample]?, err: NSError?) -> Void in
if err != nil {
// ERROR Occurred, handled it
print(err)
return
}
var labelText = ""
for result in results as! [HKQuantitySample]! {
// SUCCESS, use results here
labelText += "\(result)"
}
self.displayData.text = labelText
}
))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}