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

时间:2015-07-16 10:15:52

标签: iphone swift ios8 core-motion motion-detection

我正在开展一项任务,以确定iPhone 6何时在任何方向(x,y或Z)移动(最小可能移动甚至不动摇!)。 实现这一目标的最佳方式是什么?

1 个答案:

答案 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))
}