在 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)
}
}
View Controller :
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)
}
}
}
最佳答案
让您的完成处理程序接收一系列步骤/日期对:
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)
}
如果您希望查询类也保留此信息,请将成员变量设置为相同类型的数组并将结果存储在其中并将其传递给回调。
关于ios - 如何将所有值作为 NSArray 返回?来自完成 block 中的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27669505/