Live Updates with CMPedometer (CoreMotion)

后端 未结 1 2047
悲哀的现实
悲哀的现实 2020-12-19 13:00

I\'ve found very limited resources on this topic (CMPedometer). I was wondering if anyone here has managed to get this to work properly. My code is fairly simple, and has mo

相关标签:
1条回答
  • 2020-12-19 13:26

    I can only confirm your findings. I also wanted to get "true" realtime information. As it seems at this point, the API is not capable of this; even by forcing the updates into a queue, sync, async, etc.

    For references and others with this question, here is the code I use based on Swift 3 and Xcode 8.2. I simply apply this portion of code in the concerned viewcontroller, after checking the CMPedometer.isStepCountingAvailable().

    As you can see, I've included a small animation to update the UILabel in a more fluid manner.

        // Steps update in near realtime - UILabel
        self.pedoMeter.startUpdates(from: midnightOfToday) { (data: CMPedometerData?, error) -> Void in
    
            DispatchQueue.main.async(execute: { () -> Void in
                if(error == nil){
                    self.todaySteps.text = "\(data!.numberOfSteps)"
                    // Animate the changes of numbers in the UILabel
                    UILabel.transition(with: self.todaySteps,
                                       duration: 0.50,
                                       options: .transitionCrossDissolve,
                                       animations: nil,
                                       completion: nil)
                }
            })
        }
    
    0 讨论(0)
提交回复
热议问题