Some questions about using CMMotion in swiftUI

119 Views Asked by At

I want to write a code to retrieve Iphone motion data in Swift's MVVM mode, but I get an error in line 15 of my Model file:

Escaping closure captures mutating 'self' parameter <<

import Foundation
import CoreMotion

struct recoderModel {
    private let motion = CMMotionManager()
    private let queue = OperationQueue()
    private(set) var attitude: Attitude
    lazy var handler: CMDeviceMotionHandler = {(motionData: CMDeviceMotion?, error: Error?) -> Void in
        storeMotionData(data: motionData, error: error)
    }
    mutating func startQueuedUpdates() {
       if motion.isDeviceMotionAvailable {
          motion.deviceMotionUpdateInterval = 1.0 / 60.0
          motion.showsDeviceMovementDisplay = true
          motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical,
                                               to: self.queue, withHandler: handler)
       }
    }
    mutating func storeMotionData(data: CMDeviceMotion?, error: Error?) {
        // Make sure the data is valid before accessing it.
        if let validData = data {
            // Get the attitude relative to the magnetic north reference frame.
            let roll = validData.attitude.roll
            let pitch = validData.attitude.pitch
            let yaw = validData.attitude.yaw
           
            attitude.pitch = pitch
            attitude.roll = roll
            attitude.yaw = yaw
            // Use the motion data in your app.
        }
    }
    struct Attitude {
        var pitch: Double = 0.0
        var roll: Double = 0.0
        var yaw: Double = 0.0
    }
}
1

There are 1 best solutions below

1
Paul Nelson On

Did you try changing

          motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical,
                                               to: self.queue, withHandler: handler)

to

          motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical,
                                               to: self.queue, withHandler: self.handler)