调用时不打印 CMMotionActivityManager 活动

CMMotionActivityManager Activities Not Printing When Calling

我确保将 Motion 添加到我的 plist 中。不确定我哪里出错了。

下面是我的代码:

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")
    }

}

在这种情况下(为了使该视图起作用),解决方法是将管理器设置为 属性

struct Settings: View {
    let motionActivityManager = CMMotionActivityManager()

    // ... other code

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

    // ... other code

但通常您必须将 motionActivityManager 放置在应用程序级别的某处(可能包装在自定义管理器 class 中),因为 startActivityUpdates(to:) 只能有一个处理程序。因此,您需要自己设置一次处理程序,然后 process/transform 进入您的应用程序范围 notifications/events。