2014-12-27 78 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

相關問題