Swift 等待异步请求完成

Swift await for async request to complete

我有以下函数,我想通过它 return 一个 Int

  private func queryPedometerSteps(currentStartDate: Date, currentLastDate: Date) -> Int {
    var stepsGiven = 0
    pedometer.queryPedometerData(from: currentStartDate, to: currentLastDate){data, error in
      guard let pedometerData = data else { return }
      let steps = pedometerData.numberOfSteps.intValue
      print("entered query from \(currentStartDate) to \(currentLastDate) and stepped \(steps)")
      stepsGiven = steps
    }
    return stepsGiven
  }

我正在使用这个函数来return步骤,通过它分配给一个变量,然后将它用于另一个函数,就像这样

let numberOfStepsBetweenDates = queryPedometerSteps(currentStartDate: currentStartDate, currentLastDate: currentLastDate)
anotherCall(numberOfStepsBetweenDates: Int)

我希望 pedometer.queryPedometerData 在 return 给定的步骤之前完成。代码原样,函数总是 returns 0。我已经尝试过调度组和信号量,但由于某种原因,当我使用它们时代码停止工作。有人知道如何做到这一点吗?谢谢!!!

像这样更改函数:

private func queryPedometerSteps(currentStartDate: Date, 
                                 currentLastDate: Date,
                                 completion: (Int?) -> Void) {
  pedometer.queryPedometerData(from: currentStartDate, to: currentLastDate) { data, error in
    guard let pedometerData = data else { return completion(nil) }
    let steps = pedometerData.numberOfSteps.intValue
    print("entered query from \(currentStartDate) to \(currentLastDate) and stepped \(steps)")
    completion(steps)
  }
}

您的调用代码将如下所示:

queryPedometerSteps(currentStartDate: currentStartDate, currentLastDate: currentLastDate) { steps in 
  guard let steps = steps else { return }
  anotherCall(numberOfStepsBetweenDates: steps)
}

(您可能必须将闭包标记为 @escaping - 我还没有检查计步器 API)