How do I detect when someone shakes an iPhone?

后端 未结 16 2188
后悔当初
后悔当初 2020-11-22 06:41

I want to react when somebody shakes the iPhone. I don\'t particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know h

16条回答
  •  面向向阳花
    2020-11-22 06:58

    First off, I know this is an old post, but it is still relevant, and I found that the two highest voted answers did not detect the shake as early as possible. This is how to do it:

    1. Link CoreMotion to your project in the target's build phases: CoreMotion
    2. In your ViewController:

      - (BOOL)canBecomeFirstResponder {
          return YES;
      }
      
      - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
      {
          if (motion == UIEventSubtypeMotionShake) {
              // Shake detected.
          }
      }
      

提交回复
热议问题