我正在使用 CMPedomer 收集步数数据。
if CMPedometer.isStepCountingAvailable() {
print("Step counting is available...")
let startDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())
let endDate = Date()
CMPedometer().queryPedometerData(from: beforeDate!, to: Date()) { [weak self] (data, error) in
print("Handler (data):")
guard let activityData = data, error == nil else {
print("There was an error getting the data: \(error!)")
return
}
todayStepCount = Int(truncating: activityData.numberOfSteps )
todayDistanceCount = Double(truncating: activityData.distance ?? 0.0)
todayFloorCount = Int(truncating: activityData.floorsAscended ?? 0)
print(activityData)
}
}
此功能在主应用程序中运行良好。在 Widget 中不起作用。
我调试小部件。这个 queryPedometerData 被调用但没有进入这个函数并且不打印任何内容。
CMPedometer().queryPedometerData(from: beforeDate!, to: Date()) { [weak self] (data, error) in
我首先通过定义 pedometer 实例在小部件中修复了相同的问题。
class Test {
private let pedometer = CMPedometer()
func stepCount(completion: @escaping(Int?) -> Void) {
guard CMPedometer.isStepCountingAvailable() else {
completion(0)
return
}
let calendar = Calendar.current
let now = Date()
let startOfDay = calendar.startOfDay(for: now)
pedometer.queryPedometerData(from: startOfDay, to: now) { (pedometerData, error) in
if let stepCount = pedometerData?.numberOfSteps {
completion(stepCount as? Int)
} else {
completion(0)
}
}
}
}
可能和内存释放有关。 这是 ChatGPT 的原因。
如果您立即创建并使用实例,例如 CMPedometer().queryPedometerData,作用域将终止并且 CMPedometer 实例将被释放。