UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Unable to retrive simple value from CMPedometer handler

Forums > SwiftUI

Hello

I'm trying to create a simple live updated pedometer using CMPedometer in swiftUI. The problem that I'm having is that the function startUpdates() does not execute.

I have made sure everything is set in info.plist, It does work when I'm testing the queryPedometerData function.

I'm kind of new to swift, but it's probably something simple that I'm missing.

import SwiftUI
import CoreMotion

    struct ContentView: View {

        //Pedometer variables
        let pedometer = CMPedometer()
        @State var steps: Int?

        var body: some View {
            Text(steps != nil ? "\(steps!) Steps" : "data error")
                .onAppear{
                    initializePedometer()
                }
        }

        var isPedometerAvailable: Bool{
            return CMPedometer.isPedometerEventTrackingAvailable() &&
                CMPedometer.isDistanceAvailable() && CMPedometer.isStepCountingAvailable()
        }

        func initializePedometer(){
            if CMPedometer.isStepCountingAvailable(){
                pedometer.startUpdates(from: Date()){ (pedData,error) in
                    guard let pedData = pedData, error == nil else { return }
                    steps = pedData.numberOfSteps.intValue
                }
            }
        }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

2      

It might be in func initializePedometer() you put if CMPedometer.isStepCountingAvailable() { try if isPedometerAvailable {

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.