运动管理器不工作

motion manager not working

我正在尝试获取设备运动(俯仰、滚动、偏航),但我的函数 handleDeviceMotionUpdate 未启动(我正在 iphone 5s 上尝试),这是代码:

import UIKit
import CoreMotion

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()






    var motionManager = CMMotionManager()
    motionManager.startDeviceMotionUpdates()
    motionManager.deviceMotionUpdateInterval = 0.1


    motionManager.startDeviceMotionUpdatesToQueue(
        NSOperationQueue.currentQueue()!, withHandler: {
            (deviceMotion, error) -> Void in

            if(error == nil) {
                self.DeviceMotionUpdate(deviceMotion!)
            } else {
                print("error")
            }
    })

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func DeviceMotionUpdate(deviceMotion:CMDeviceMotion) {
    print("function launched")
    var attitude = deviceMotion.attitude
    var roll = (attitude.roll)
    var pitch = (attitude.pitch)
    var yaw = (attitude.yaw)
    print("Roll: \(roll), Pitch: \(pitch), Yaw:  (yaw)")

}



}

我没有在 startDeviceMotionUpdatesToQueue 中收到错误。我在 motionManager.deviceMotionActive 和 motionManager.deviceMotionAvailable

上都是真的

您的 motionManager 可能在完成 运行 viewDidLoad 方法后被销毁。尝试将 motionManager 设为 class 属性。

class ViewController: UIViewController {
    var motionManager = CMMotionManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.motionManager.startDeviceMotionUpdates()

        ...