How to Update Magnetometer Data In WatchOS SwiftUI?

Hi All,


Thanks in advance for taking the time to check this out. I was hoping someone could help me with this problem I'm having trouble getting past.


So I'm using SwiftUI to create a standalone watch app on watchOS 6.1, and am trying to get the magnetometer data to read on the screen and update as I move the watch.


When I run the app on my watch, it shows the text, but is not updating or changing values from 0.000000.


Here is what my code looks like right now.


MagnetometerView.swift


import SwiftUI

struct MagnetometerView: View {

    @ObservedObject
    var motion: MotionManager

    var body: some View {
        VStack {
            Text("Magnetometer Data")
            Text("X: \(motion.x)")
            Text("Y: \(motion.y)")
            Text("Z: \(motion.z)")
        }
    }
}

struct MagnetometerView_Previews: PreviewProvider {
    static var previews: some View {
        MagnetometerView(motion: MotionManager())
    }
}


MotionManager.swift file

import Foundation
import Combine
import CoreMotion

class MotionManager: ObservableObject {

    private var motionManager: CMMotionManager

    @Published
    var x: Double = 0.0
    @Published
    var y: Double = 0.0
    @Published
    var z: Double = 0.0


    init() {
        self.motionManager = CMMotionManager()
        self.motionManager.magnetometerUpdateInterval = 1/60
        self.motionManager.startMagnetometerUpdates(to: .main) { (magnetometerData, error) in
            guard error == nil else {
                print(error!)
                return
            }

            if let magnetData = magnetometerData {
                self.x = magnetData.magneticField.x
                self.y = magnetData.magneticField.y
                self.z = magnetData.magneticField.z
            }

        }

    }
}


When I run the app, it builds and shows the view properly, but the values do not change from 0.


Any advice would be greatly appreciated,

Thank you in advance!

Similar problem. I'm trying to get magnetometer data on Apple Watch 6 or 7 but isMagnetometerAvailable returns false. At the same time, the app for logging sensor data (SensorLog) can record magnetometer on the watch in some way.

How to Update Magnetometer Data In WatchOS SwiftUI?
 
 
Q