Search code examples
iosdetectionmotion

iOS Motion Detection: Motion Detection Sensitivity Levels


I have a simple question. I'm trying to detect when a user shakes the iPhone. I have the standard code in place to detect the motion and this works no problem. However, in testing this on my actual phone, I've realized that you have to shake the device quite hard to get the motion detection to trigger. I would like to know if there is a way to implement a level of sensitivity checking. For example, a way to detect if a user lightly shakes the device or somewhere between light and hard shake. This will be targeted towards iOS 7 so any tips or advice that is not deprecated from older iOS version would be greatly appreciated. I've done my googling but have yet to find any good solutions to this problem (If there are any.)

Thanks!

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(motion == UIEventSubtypeMotionShake)
    {
       //Detected motion, do something about it 
       //at this point.
    }
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

Solution

  • Use core motion.

    Link your binary with the CoreMotion framework. Include

    #import <CoreMotion/CoreMotion.h>

    in your class.

    Create an instance of CMMotionManager.

    Set the deviceMotionUpdateInterval property to a suitable value. Then call startDeviceMotionUpdatesToQueue.

    You will get continuous updates inside the block, which include acceleration, magnetic field, rotation, etc. You will get the data you require.

    One thing to be taken care of is that the update shall be so rapid if the interval is too small, and hence you will have to employ suitable logic to handle the same.