Detecting device shake using iOS 8 and Swift

To respond to a shake gesture in iOS 8 using Swift, you must override three methods in the ViewController that will respond to the shake: viewDidAppear(animated: Bool), canBecomeFirstResponder() -> Bool and motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!)

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    override func viewDidAppear(animated: Bool) {
    override func canBecomeFirstResponder() -> Bool {
        return true
    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!) {
        if(event.subtype == UIEventSubtype.MotionShake) {
            var alert = UIAlertController(title: "Shaken",
                message: "Not Stirred",
                preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK",
                style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)

Leave a Reply

Your email address will not be published. Required fields are marked *