in this example:
struct ContentView: View {
var body: some View {
Button("Tap Me") {
// Action to perform when the button is tapped
print("Button was tapped!")
startAccelerometer()
}
}
}
you see the error "Cannot find 'startAccelerometer' in scope" because startAccelerometer is outside the scope of the structure ContentView (which begins at its { and ends at its }. The compiler doesn't know you mean the function called startAccelerometer inside your MyViewController class. That's a good thing, because names are often re-used in different places in code.
In your more recent example, your ContentView doesn't refer to startAccelerometer, and there is no code to call it (what happened to your button? Your screen is blank and white because that's what an empty content view looks like. Your startAccelerometer function, if called, would call itself again and again until your program ran out of stack space and was terminated.
You usually don't need a UIViewController in a SwiftUI app. Interfacing between SwiftUI and UIKit is an advanced topic.
I suggest you take a step back and review a few simple SwiftUI projects so you can get the hang of drawing into a window and responding to clicks and drags inside a view. You should also try to learn about basic programming concepts like scope.
Or, if you are just desperate to see what is going on with the accelerometer, here is a quick and dirty program which will print the results into the debugger console in Xcode on your Mac while the program runs on your phone. It is not a good example of app design (most code samples are not)
import SwiftUI
import CoreMotion
struct ContentView: View {
@State private var motionManager: CMMotionManager = CMMotionManager()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
.onAppear() {
if motionManager.isAccelerometerAvailable {
motionManager.accelerometerUpdateInterval = 0.1 // 10 updates per second
motionManager.startAccelerometerUpdates(to: .main) { (data, error) in
guard let accelerometerData = data else { return }
let x = accelerometerData.acceleration.x
let y = accelerometerData.acceleration.y
let z = accelerometerData.acceleration.z
// Process the x, y, and z acceleration values here
print("X: \(x), Y: \(y), Z: \(z)")
}
}
}
}
}