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 変数は迅速にオプションであると考えました (それらは nil になる可能性があるため)。

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 に答える