如何检测 iPhone 6 设备的运动? (确定 iPhone 设备是否移动 - x、y、z 上的最小可能运动-)

how to detect motion of iPhone 6 device? (determine whether iPhone device moved or not -smallest possible motion on x,y,z- )

我正在执行一项任务,以确定 iPhone 6 何时在任何方向(x、y 或 Z)移动(最小的可能移动甚至连摇晃都没有!)。 实现该目标的最佳方法是什么?

我用过这段代码,发现它很有用,它包含四个功能: - 启动运动管理器 - 停止运动经理 - 更新运动管理器 - 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))
}