To detect a shake gesture in iOS UIKit provides three different methods, let’s see them one by one.
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { // code you want to implement }
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { // Code you want to implement. }
override func motionCancelled(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { // code you want to implement. }
Now let’s add some code in our motionBegan method,
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { print(motion) if motion == .motionShake { print("shake was detected") } }
Also add “self.becomeFirstResponder()” in your viewDidLoad() method. When we run the above code on simulator, and use debug to produce a shake gesture, below is the result that’s produced. We can modify the code above according to our use and perform different operations In our app.