0

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:

enter image description here

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.
    }


}
Ahad Sheriff
  • 1,829
  • 8
  • 24
  • 46
  • Have you looked up String formatting for Swift online? There are a lot of links and references on SO. check out: http://stackoverflow.com/questions/29749187/is-there-an-equivalent-to-the-string-function-stringformat-using-swift-fo PS, can you post the code the you're trying to format the string with? – Lukesivi Nov 09 '15 at 20:32
  • The output isn't weird btw. It's the time and date + the calorie count. What you can do is format the text by using `String(format: "%02d/%02d", varOne, varTwo)` and you define `varOne` and `varTwo` as the time, calorie intake, etc. Print the variable that outputs that into the logs and then break it down. – Lukesivi Nov 09 '15 at 20:38
  • Above is really all the code I have, I'm just trying to read the Active Energy data from HealthKit and trying to get it to display on the screen – Ahad Sheriff Nov 09 '15 at 20:43
  • I mean all I want it to do is to have one number on the screen and have that number update live with the active energy from HealthKit I feel like the solution should be super simple but I just don't know how to implement it – Ahad Sheriff Nov 09 '15 at 20:44
  • Do you want to format the text or update live? I'm writing an answer for formatting the date and time. Using that model you can also format the calorie intake, etc. – Lukesivi Nov 09 '15 at 20:45
  • Both for sure, I want the app to just track the health data in real time but just print out one number (hence formatting the text) – Ahad Sheriff Nov 09 '15 at 20:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/94645/discussion-between-lukesivi-and-ahad-sheriff). – Lukesivi Nov 09 '15 at 20:46

0 Answers0