iOS Motion Detection: Motion Detection Sensitivity Levels

后端 未结 4 1505
我在风中等你
我在风中等你 2021-02-05 18:24

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 test

4条回答
  •  我寻月下人不归
    2021-02-05 18:39

    Here is the solution I found. This works well but you do have to play with the deviceMotionUpdateInterval time value as well as the accelerationThreshold which can be tricky to get a fine balancing act for a actual "light shake" vs "picking up the phone and moving it closer to your face etc..." There might be better ways but here is one to start. Inside of my view didLoad I did something like this:

    #import  //do not forget to link the CoreMotion framework to your project
    #define accelerationThreshold  0.30 // or whatever is appropriate - play around with different values
    
    -(void)viewDidLoad
    {
          CMMotionManager *motionManager; 
    
          motionManager = [[CMMotionManager alloc] init];
          motionManager.deviceMotionUpdateInterval = 1;
    
          [motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]  withHandler:^(CMDeviceMotion *motion, NSError *error)
                 {
                    [self motionMethod:motion];
                 }];
    }
    
    -(void)motionMethod:(CMDeviceMotion *)deviceMotion
    {
        CMAcceleration userAcceleration = deviceMotion.userAcceleration;
        if (fabs(userAcceleration.x) > accelerationThreshold
            || fabs(userAcceleration.y) > accelerationThreshold
            || fabs(userAcceleration.z) > accelerationThreshold)
            {
               //Motion detected, handle it with method calls or additional
               //logic here.
               [self foo];
            }
    }
    

提交回复
热议问题