Andrea
Andrea

Reputation: 31

queryPedometerData returns nil steps even if there are steps logged

I want to retrieve steps from 1h ago. I don't need to do anything special, I just need to know how many steps a user has done since the last hour.

Even though my iPhone has some steps logged, the query to retrieve the number of steps returns "nil".

This is the code:

   let calendar = Calendar.current //calendar now, to be used in calculating the h in the past
let beforeDate = calendar.date(byAdding: .hour, value: -1, to: Date())



let pedometer = CMPedometer() //define pedometer

    if CMPedometer.isStepCountingAvailable() == true {print("steps available")}else{print("steps not available")}

    pedometer.queryPedometerData(from: beforeDate!, to: Date(), withHandler: { (pedometerData, error) in
        if let pedData = pedometerData{
            self.dateLabel.text = "Steps:\(pedData.numberOfSteps)"
        }else {
            self.dateLabel.text = "error)"
            print(beforeDate)

        }
    })
}

And this is the date format that I put in the query:

2018-03-16 12:59:17 +0000

What is wrong?

Upvotes: 0

Views: 849

Answers (1)

matt
matt

Reputation: 534987

One possible problem is that your CMPedometer object is stored only in a local variable. pedometer.queryPedometerData runs asynchronously, so this object needs to persist long enough to fulfill the query. But it can't do that if it is a local variable; it vanishes before the data can even be fetched. Try making pedometer a persistent instance property instead.

Also be aware that you don't know what queue the data will be delivered on. You need to step out to the main queue in order to talk to the interface, and you are failing to do that.

Upvotes: 2

Related Questions