2014-06-09 53 views
9

我嘗試在Swift中使用運動管理器,但我的更新塊內部的日誌從不打印。Motion Manager在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實現工作正常。有誰知道爲什麼我的更新塊沒有被調用?

回答

22

這是因爲運動管理器實例在方法返回時被拋出。你應該在你的課堂上創造一個屬性來包含運動管理器。此外,它看起來像只更改管理器的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

我認爲所有的OBJ-C變量在迅速自選(因爲它們可以爲空),所以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

States

o型o f塊回調用於處理設備運動數據。

宣言 SWIFT typealias CMDeviceMotionHandler =(CMDeviceMotion!NSError!) - >虛空