0

There seems to be a bug in the CMPedometer queryPedometerData() method. The method is returning 0 steps for certain end times, but the same query with the timestamp 1 second higher or lower returns the correct number of steps

e.g.

self.getStepsBetweenDates(NSDate(timeIntervalSince1970: 1543392126) as Date, date2:  NSDate(timeIntervalSince1970: 1543393044) as Date) returns (Int) 1488

self.getStepsBetweenDates(NSDate(timeIntervalSince1970: 1543392126) as Date, date2:  NSDate(timeIntervalSince1970: 1543393045) as Date) returns (Int) 0

self.getStepsBetweenDates(NSDate(timeIntervalSince1970: 1543392126) as Date, date2:  NSDate(timeIntervalSince1970: 1543393046) as Date) returns (Int) 1488

getStepsBetweenDates method looks like this

func getStepsBetweenDates(_ date1: Date, date2: Date) -> Int{

    let group = DispatchGroup()
    group.enter()

    var steps = 0

    self.pedometer.queryPedometerData(from: date1, to: date2, withHandler: {
      pData, error in
      if let e = error{
          print("Error querying pedometer", e.localizedDescription)
      }else{
        if let data = pData{
          steps = Int(data.numberOfSteps)
        }
        group.leave()
      }
    })

    _ = group.wait(timeout: DispatchTime.distantFuture)
    return steps

  }
4

1 回答 1

1

queryPedometerData是异步调用

通常,您不想返回getStepsBetweenDates调用中的步骤,因为它是异步的。

如果您将其更改为var steps = 0var steps = [some random int]那么由于设置了竞争条件,您很可能会得到该数字而不是 0。

更理想的做法是将您的代码实现为闭包/回调或其他形式的异步处理。

例如:

self.pedometer.queryPedometerData(from: date1, to: date2) { (data, error) in
  // Do something here with data.numberOfSteps    
}

这是 Medium 上关于异步代码的文章:

https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f

于 2019-02-15T16:22:39.760 回答