【问题标题】:Motion Manager is not working in Swift运动管理器在 Swift 中不起作用
【发布时间】:2014-07-29 15:10:44
【问题描述】:

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

【问题讨论】:

    标签: ios swift core-motion cmmotionmanager


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我认为所有 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

      国家

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-25
        • 2013-05-05
        • 1970-01-01
        相关资源
        最近更新 更多