Motion Manager无法在Swift中运行

时间:2014-06-09 05:28:28

标签: ios swift core-motion cmmotionmanager

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

    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实现工作正常。有谁知道为什么我的更新块没有被调用?

2 个答案:

答案 0 :(得分:24)

那是因为当方法返回时,运动管理器实例被抛出。您应该在类上创建一个属性以包含运动管理器。此外,您似乎只是更改了管理器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
    }
}

答案 1 :(得分:0)

我认为所有obj-c变量都是swift中的选项(因为它们可以是nil)所以NSOperationQueue应该是一个爆炸:

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

Apple文档:

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

用于处理设备运动数据的块回调类型。

宣言 迅速 typealias CMDeviceMotionHandler =(CMDeviceMotion!,NSError!) - >空隙

相关问题