Swift 等待异步请求完成

时间:2021-03-16 16:50:29

标签: swift core-motion

我有以下函数,我想通过它返回一个 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
  }

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

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

我希望pedometer.queryPedometerData 在返回stepsGive 之前完成。代码本身,该函数总是返回 0。我已经尝试过 Dispatch 组和信号量,但是由于某种原因,当我使用这些时代码停止工作。有人知道如何做到这一点吗?谢谢!!!

1 个答案:

答案 0 :(得分:1)

像这样改变函数:

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)