运动管理器在Swift中无法工作

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

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
    }
}

0

我认为在Swift中所有的Objective-C变量都是可选的(因为它们可以为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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接