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!