如何将完成处理程序的结果分配给变量?

时间:2014-12-27 19:13:41

标签: ios

我正在尝试从完成处理程序中分配结果,以便我可以使用它在图形库中绘图。目前数据打印到控制台为 控制台输出:

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

- 问题:我需要在图中使用此数据。如何在ViewController或QueryHKArray2中更改我的代码,以便我可以将数据分配给类似于此的变量:

  • var dateArray = query.performHKQuery()。date
  • var stepArray = query.performHKQuery()。stepCount

非常感谢任何帮助!

的ViewController:

import UIKit


class ViewControllerArray2: UIViewController {

    var query = QueryHKArray2()

    override func viewDidLoad() {
        super.viewDidLoad()

        printStepsAndDate()
    }


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

        }
    }

QueryHKArray2类:

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

1 个答案:

答案 0 :(得分:1)

您可以循环浏览stepCount并获取tuple

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

    }
}