Motion Manager不在Swift中工作

我尝试在Swift中使用运动pipe理器,但是我的更新块里面的日志从不打印。

var motionManager: CMMotionManager = CMMotionManager() motionManager.accelerometerUpdateInterval = 0.01 println(motionManager.deviceMotionAvailable) // print true println(motionManager.deviceMotionActive) // print false motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{ deviceManager, error in println("Test") // no print }) println(motionManager.deviceMotionActive) // print false 

我的Objective-C实现工作正常。 有谁知道为什么我的更新块没有被调用?

这是因为运动pipe理器实例在方法返回时被抛出。 你应该在你的课堂上创造一个财产来包含运动pipe理器。 此外,它看起来像你只是改变经理的accelerometerUpdateInterval ,然后监视设备的运动变化。 您应该设置deviceMotionUpdateInterval属性。

 import CoreMotion class ViewController: UIViewController { let motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() motionManager.deviceMotionUpdateInterval = 0.01 motionManager.startDeviceMotionUpdates(to: OperationQueue.current!) { deviceManager, error in print("Test") // no print } print(motionManager.isDeviceMotionActive) // print false } } 

我认为所有的obj-cvariables都是swift中的可选项(因为它们可以为零),所以NSOperationQueue应该这样做:

 MotionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue!.currentQueue(),withHandler:{deviceManager,error in println("test")}) 

苹果文档在这里:

https://developer.apple.com/library/ios/documentation/CoreMotion/Reference/CMMotionManager_Class/#//apple_ref/swift/tdef/CMDeviceMotionHandler

状态

处理设备运动数据的块callbacktypes。

声明SWIFT typealias CMDeviceMotionHandler =(CMDeviceMotion!,NSError!) – > void