iosswift3swift4core-motionpedometer

Core Motion Pedometer Save Timer Data when in Background


I've started to play with the Pedometer and it's working just fine. I've made a timmer that will show me the working out time and it's working perfectly tracking the Activity Type. The Pedometer will update in the background automatically, however, the timmer will not. I know I have to use a Notification for applicationDidEnterBackground. I can find out how much time elapsed since the app went into the background till now so I can make the difference in time.

My problem is: How would I know how much of that time is WALKING & RUNNING? Because it's going to give the time for all Events. Does anybody know a solution to achieve this?


Solution

  • Managed to solve the problem. Each time this function is triggered it means the user has activity:

    //START GETTING UPDATES
    private func startUpdating() {
        if CMMotionActivityManager.isActivityAvailable() {
            startTrackingActivityType()
        }
    
        if CMPedometer.isStepCountingAvailable() {
            startCountingSteps()
        }
    }
    

    In this function startCountingSteps(), I placed an array that will append one item each time it's triggered if steps count is bigger than 1, for each second. Meaning it's either Walking or Running.

    I saved the time in seconds when the user enters background and get the current time when the user opens up the app again. The current number of seconds + array.count = Current elapsed working out time.