如何将所有值作为NSArray返回?来自完成块中的查询

时间:2014-12-27 17:08:40

标签: ios swift

在QueryHK中,我为步骤和相应的日期运行HealthKit查询。我在完成处理程序中返回值。在ViewController中,我声明完成。我的问题是该方法只返回样本中迭代样本的最后一个值。

  • 问题我希望所有在完成时返回的数据,而不仅仅是最后一个值..如何在NSArray中返回查询中的所有数据?

QueryHK.swift:

import UIKit
import HealthKit

class QueryHK: NSObject {

var steps = Double()
var date = NSDate()

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

            for sample in samples as [HKQuantitySample]
            {

                self.steps  = sample.quantity.doubleValueForUnit(stepsUnit)
                self.date  = sample.startDate

            }
            // Calling the completion handler with the results here
            completion(steps: self.steps, date: self.date)
    }
    healthKitManager.healthStore.executeQuery(sampleQuery)
}
}

的ViewController:

import UIKit

class ViewController: UIViewController {
        var dt = NSDate()
        var stp = Double()

    var query = QueryHK()

    override func viewDidLoad() {
        super.viewDidLoad()

        printStepsAndDate()
    }

    func printStepsAndDate() {
        query.performHKQuery() {
            (steps, date) in
            self.stp = steps
            self.dt = date
            println(self.stp)
            println(self.dt)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

让您的完成处理程序收到一系列步骤/日期对:

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

(你可以传递两个数组,一个步骤和一个日期,但我觉得传递一对数组比较清楚,因为这两个数据并列在一起)

然后构建一组步数和日期对:

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

如果您希望查询类也保留此信息,请将成员变量设置为相同类型的数组,并将结果存储在该数组中,并将其传递给回调。