我正在开展一项任务,以确定iPhone 6何时在任何方向(x,y或Z)移动(最小可能移动甚至不动摇!)。 实现这一目标的最佳方式是什么?
答案 0 :(得分:3)
我使用了这段代码并发现它很有用,它包含四个函数: - 启动运动管理器 - 停止运动经理 - 更新动画管理器 - magnitudeFromAttitude
import CoreMotion
let motionManager: CMMotionManager = CMMotionManager()
var initialAttitude : CMAttitude!
//start motion manager
func StartMotionManager () {
if !motionManager.deviceMotionActive {
motionManager.deviceMotionUpdateInterval = 1
motionManager.startDeviceMotionUpdates()
}
}
//stop motion manager
func stopMotionManager ()
{
if motionManager.deviceMotionActive
{
motionManager.stopDeviceMotionUpdates()
}
}
//update motion manager
func updateMotionManager (var x : UIViewController)
{
if motionManager.deviceMotionAvailable {
//sleep(2)
initialAttitude = motionManager.deviceMotion.attitude
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{
[weak x] (data: CMDeviceMotion!, error: NSError!) in
data.attitude.multiplyByInverseOfAttitude(initialAttitude)
// calculate magnitude of the change from our initial attitude
let magnitude = magnitudeFromAttitude(data.attitude) ?? 0
let initMagnitude = magnitudeFromAttitude(initialAttitude) ?? 0
if magnitude > 0.1 // threshold
{
// Device has moved !
// put the code which should fire upon device moving write here
initialAttitude = motionManager.deviceMotion.attitude
}
})
println(motionManager.deviceMotionActive) // print false
}
}
// get magnitude of vector via Pythagorean theorem
func magnitudeFromAttitude(attitude: CMAttitude) -> Double {
return sqrt(pow(attitude.roll, 2) + pow(attitude.yaw, 2) + pow(attitude.pitch, 2))
}