NovelPomodoro
NovelPomodoro

Reputation: 67

CMMotionActivityManager Activities Not Printing When Calling

I made sure to add Motion to my plist. Not sure where I'm going wrong.

Below is my code:

import SwiftUI 
import CoreMotion

struct Settings: View {

    @State var walk = ""
    @State var run = ""
    @State var unk = ""

    var body: some View {
        VStack{
        Text("Stationary: \(walk)")
        Text("Walking: \(run)")
            Text("Unknown: \(unk)")

            Button(action: {
                self.startTest()
            }) {
                Text("Start")
            }

        }
    }

    func startTest(){
        let motionActivityManager = CMMotionActivityManager()

        if CMMotionActivityManager.isActivityAvailable() {
            motionActivityManager.startActivityUpdates(to: OperationQueue.main) { (motion) in

                self.walk = (motion?.stationary)! ? "True" : "False"
                self.run = (motion?.walking)! ? "True" : "False"
                self.unk = (motion?.unknown)! ? "True" : "False"
                print(self.walk)
                print(self.run)
                print(self.unk)
            }
        }
        print("NONE")
    }

}

Upvotes: 1

Views: 773

Answers (1)

Asperi
Asperi

Reputation: 257663

In this case (to make this view work) the fix is to make manager as property

struct Settings: View {
    let motionActivityManager = CMMotionActivityManager()

    // ... other code

    func startTest(){
        if CMMotionActivityManager.isActivityAvailable() {

    // ... other code

but in general you have to place motionActivityManager somewhere at application-wide level (probably wrap in custom manager class), because startActivityUpdates(to:) can have only one hander. So you need to set up handler once and process/transform into your application wide notifications/events by yourself.

Upvotes: 1

Related Questions