Detect shake gesture IOS Swift Detect shake gesture IOS Swift ios ios

Detect shake gesture IOS Swift


Swift3 ios10:

override func viewDidLoad() {    super.viewDidLoad()    self.becomeFirstResponder() // To get shake gesture}// We are willing to become first responder to get shake motionoverride var canBecomeFirstResponder: Bool {    get {        return true    }}// Enable detection of shake motionoverride func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {    if motion == .motionShake {        print("Why are you shaking me?")    }}


Super easy to implement:

1) Let iOS know which view controller is the first in the responder chain:

override func viewDidLoad() {    super.viewDidLoad()    self.becomeFirstResponder()}   override func canBecomeFirstResponder() -> Bool {    return true}

2) Handle the event in some fashion:

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {    if(event.subtype == UIEventSubtype.MotionShake) {        print("You shook me, now what")    }}


Swift 5

Just add following methods to ViewController and execute the code

override func becomeFirstResponder() -> Bool {    return true}override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){    if motion == .motionShake {        print("Shake Gesture Detected")        //show some alert here    }}