KML
KML

Reputation: 2322

How can I assign result from completion handler to a variable?

I am trying to assign the result from a completion handler in such a way that I can use it to plot in a graph library. Currently the data print to the console as Console Output:

[(200.0, 2014-12-26 12:44:00 +0000), 300.0, 2014-12-25 12:44:00 +0000)]

- Question: I need to use this data in a plot. How can I change my code in ViewController or QueryHKArray2 so that I can assign the data to a variable similar to this:

Any help is much appreciated !

ViewController:

import UIKit


class ViewControllerArray2: UIViewController {

    var query = QueryHKArray2()

    override func viewDidLoad() {
        super.viewDidLoad()

        printStepsAndDate()
    }


    func printStepsAndDate() {
        query.performHKQuery() { stepCount in
            println(stepCount)

        }
    }

QueryHKArray2 class:

import UIKit 
import HealthKit

class QueryHKArray2: NSObject {

    func performHKQuery(completion: ([(steps: Double, date: NSDate)]) -> Void) {

        let healthKitManager = HealthKitManager.sharedInstance
        let stepsSample = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
        let stepsUnit = HKUnit.countUnit()
        let sampleQuery = HKSampleQuery(
            sampleType: stepsSample,
            predicate: nil,
            limit: 0,
            sortDescriptors: nil)
            {
                (sampleQuery, samples, error) in

                if let samples = samples as? [HKQuantitySample] {

                    let steps = samples.map { (sample: HKQuantitySample)->(steps: Double, date: NSDate) in
                        let stepCount = sample.quantity.doubleValueForUnit(stepsUnit)
                        let date = sample.startDate
                        return (steps: stepCount, date: date)
                    }

                    completion(steps)
                }

        }
        healthKitManager.healthStore.executeQuery(sampleQuery)
    } }

Upvotes: 0

Views: 158

Answers (1)

codester
codester

Reputation: 37189

You can loop through stepCount and get the tuple values

func printStepsAndDate() {
    var dateArray:[NSDate] = []
    var stepArray:[Double]= []
    query.performHKQuery() { stepCount in
        for temp in stepCount {
          stepArray.append(temp.steps)
          dateArray.append(temp.date)
        }

    }
}

Upvotes: 1

Related Questions