11

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

4

2 回答 2

25

这是因为当方法返回时,运动管理器实例被抛出。您应该在您的类上创建一个属性以包含运动管理器。此外,看起来您只是在更改管理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
    }
}
于 2014-06-09T05:33:00.907 回答
0

我认为所有 obj-c 变量在 swift 中都是可选的(因为它们可以是 nil)所以 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

状态

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

声明 SWIFT typealias CMDeviceMotionHandler = (CMDeviceMotion!, NSError!) -> Void

于 2014-09-19T11:29:18.247 回答