2014-06-09 4 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 속성을 설정해야합니다.

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

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 변수 신속한에서 선택적 항목이 (가 nil이 될 수 있기 때문에) NSOperationQueue이 thusly 히 강타를해야하므로 있다고 생각

상태

유형 o f 장치 - 동작 데이터를 처리하기위한 블록 콜백.

선언 SWIFT typealias CMDeviceMotionHandler = (CMDeviceMotion! NSError!) ->

무효