gpt4 book ai didi

ios - CMPedometer queryPedometerData() 在步骤存在时返回 0 个步骤

转载 作者:行者123 更新时间:2023-11-28 14:01:19 29 4
gpt4 key购买 nike

CMPedometer queryPedometerData() 方法中似乎存在错误。该方法在某些结束时间返回 0 步,但时间戳高或低 1 秒的相同查询返回正确的步数

例如

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 方法如下所示

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

}

最佳答案

queryPedometerData 是异步调用

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

如果您将 var steps = 0 更改为 var 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

关于ios - CMPedometer queryPedometerData() 在步骤存在时返回 0 个步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517678/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com