问题描述
我尝试在Swift中使用运动管理器,但我的更新块中的日志永远不会打印。
I am try to use motion manager in Swift but the log inside my update block never prints.
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实现正常。有谁知道为什么我的更新块没有被调用?
My Objective-C implementation works fine. Does anyone know why my update block isn't being called?
推荐答案
那是因为当运动管理器实例被抛出时方法返回。您应该在类上创建一个属性以包含运动管理器。此外,您似乎只是更改了管理器的 accelerometerUpdateInterval
,然后监视设备运动更改。您应该设置 deviceMotionUpdateInterval
属性。
That's because the motion manager instance is being thrown out when the method returns. You should make a property on your class to contain the motion manager. Additionally, it looks like you were only changing the manger's accelerometerUpdateInterval
and then monitoring device motion changes. You should set the deviceMotionUpdateInterval
property instead.
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
}
}
这篇关于Motion Manager无法在Swift中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!