Search code examples
swiftmotion

Motion shake action not working anymore in swift


Hi I have hit a bit of a brick wall, I have been redesigning my menu navigation for my app. which I have managed to do. But now one of the features of my app has decided to stop functioning.

The idea is you shake your phone and it chooses a picture at random, the code separate from the app works fine, just as it has done on all previous versions of it, I even ran it quickly in it's present form on it's own just in case and it worked perfectly.

hopefully somebody can point me in the direction of where I have gone wrong.

my code is as follows;

    import Foundation
import UIKit


class cocktailChoice: UIViewController {

    @IBOutlet weak var drinkImage: UIImageView!

    var drinkNamesArray:[String] = ["cocktailList0","cocktailList1","cocktailList2","cocktailList3","cocktailList4","cocktailList5","cocktailList6","cocktailList7","cocktailList8","cocktailList9","cocktailList10","cocktailList11","cocktailList12","cocktailList13","cocktailList14","cocktailList15","cocktailList16","cocktailList17","cocktailList18","cocktailList19","cocktailList20","cocktailList21","cocktailList22","cocktailList23","cocktailList24","cocktailList25","cocktailList26","cocktailList27","cocktailList28","cocktailList29","cocktailList30","cocktailList31"]

    override func viewDidLoad() {
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {

        if motion == .motionShake{

            let firstRandomNumber = Int(arc4random_uniform(32))

            let DrinkString:String = self.drinkNamesArray[firstRandomNumber]

            self.drinkImage.image = UIImage(named: DrinkString)

        }

    }

}

it compiles with no errors, the IBOutlet is connect, it has no errors that i can see but the shake action doesn't want to play. getting very frustrating now.


Solution

  • Instead of this part if motion == .motionShake{ , can you try to use this:

    if(event.subtype == .motionShake) {
            print("Shake event!")
        }