2015-07-21 148 views
1

我有一個收集步驟數據的函數,但我需要一種方法讓它在循環之前等待它的查詢完成。我意識到有關於這個問題的其他問題,但我無法弄清楚如何解決它。功能如下:如何等待異步函數Swift

func stepsAllTime(completion: (Double, NSError?) ->()) { 
    var stopStart = true 
    while stopStart { 

     x += -1 
     // The type of data we are requesting 
     let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) 
     var daysAgo = x 
     var daysSince = x + 1 
     var daysSinceNow = -1 * daysAgo 
     checker = allTimeSteps.count 

     // Our search predicate which will fetch data from now until a day ago 
     let samplePredicate = HKQuery.predicateForSamplesWithStartDate(NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: daysAgo, toDate: NSDate(), options: nil), endDate: NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: daysSince, toDate: NSDate(), options: nil), options: .None) 

     // The actual HealthKit Query which will fetch all of the steps and sub them up for us. 
     let stepQuery = HKSampleQuery(sampleType: sampleType, predicate: samplePredicate, limit: 0, sortDescriptors: nil) { query, results, error in 
      var steps: Double = 0 


      if results?.count > 0 { 
       for result in results as! [HKQuantitySample] { 
        steps += result.quantity.doubleValueForUnit(HKUnit.countUnit()) 
       } 
      } 

      completion(steps, error) 
      self.allTimeStepsSum += steps 
      self.allTimeSteps.append(steps) 
      println("New Sum:") 
      println(self.allTimeStepsSum) 
      println("Days Since Today:") 
      println(daysSinceNow) 
      if !(self.allTimeStepsTotal > self.allTimeStepsSum) { 
       stopStart = false 
      } 
     } 
     if allTimeStepsTotal > allTimeStepsSum { 

      self.healthKitStore.executeQuery(stepQuery) 

     } 

    } 

} 

這怎麼辦? Swift中是否有某種「On Complete」函數?

+0

......你想你'stepQuery'完成關閉之前你的下一個被稱爲只是要清楚'而stopStart'通行證執行? – bsarrazin

回答

2

我假設,我的意見是準確的閱讀更多關於它。 你可能想看看一個遞歸模式,這樣的事情:

import HealthKit 

class Person { 

    var nbSteps: Double = 0 

    func fetchInfo() -> Void { 
     let sampleType = HKSampleType() 
     let samplePredicate: NSPredicate? = nil // Your predicate 
     let stepQuery = HKSampleQuery(
      sampleType: sampleType, 
      predicate: samplePredicate, 
      limit: 0, 
      sortDescriptors: nil) { (sampleQuery, object, error) -> Void in 
       self.nbSteps += 1 // or the value you're looking to add 

       dispatch_async(dispatch_get_main_queue(), {() -> Void in // Dispatch in order to keep things clean 
        self.fetchInfo() 
       }) 
     } 
    } 

}