运动经理不起作用



我试图获取设备运动(俯仰,滚动,偏航),但我的功能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 ViewController: UIViewController {
    var motionManager = CMMotionManager()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.motionManager.startDeviceMotionUpdates()
        ...

相关内容

  • 没有找到相关文章

最新更新