4

I'm working on a task to determine when the iPhone 6 is moving (smallest possible move not even a shake!) at any direction (x,y or Z) . what is the best way to achieve that?

2
  • What is your question here with this code? Jul 16, 2015 at 10:17
  • I need to know whether this is the best way or there are better alternatives
    – Alaa
    Jul 16, 2015 at 10:25

1 Answer 1

6

I used this code and found it useful, it contains four functions : - Start motion manager - Stop motion manager - Update motion manager - 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))
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.