2014-12-27 76 views
0

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

  • 问:我想在完成返回的数据的所有,而不仅仅是最后的价值..我如何从一个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

有你完成处理收到的步/日期对的数组:

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

如果你想查询类别为保留此信息,以及,使成员变量相同类型的数组,并将结果存储在和它传递给回调。

+0

谢谢你,我根据你对QueryHK类的建议更改更新了这个问题 – KML 2014-12-27 18:48:35

+0

谢谢但你不应该编辑你的问题使它成为一个新的不同的问题,你应该将它标记为已回答(如果是)和问一个新问题。 – 2014-12-27 18:51:18

+0

好 - 谢谢 - 会 - 挂 - ;) – KML 2014-12-27 18:53:19

相关问题