0

Hi I want to identify the iPhone SHAKE when user shakes their phone, either in background mode or in foreground mode of the app.

Please assist me. Thanks in advance.

3

2 Answers 2

2

Try something like this:

override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { print("Device was shaken!") } 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your quick response. i will check it.
0

The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:

class ShakingView: UIView { override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if event?.subtype == .motionShake { // Put in code here to handle shake } if super.responds(to: #selector(UIResponder.motionEnded(_:with:))) { super.motionEnded(motion, with: event) } } override var canBecomeFirstResponder: Bool { return true } 

You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).

In the view controller, you want to set this view to become first responder:

override func viewWillAppear(_ animated: Bool) { shakeView.becomeFirstResponder() super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { shakeView.resignFirstResponder() super.viewWillDisappear(animated) } 

Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!

This method works even if you set applicationSupportsShakeToEdit to NO.

For objective c version refer link How do I detect when someone shakes an iPhone?

9 Comments

ShakingView it is not a UIView at all
@Leo Dabus, here's the code that you can use in any UIView to get shake events :)
ShakingView it is just a class not a UIView
You find mistake in code than you can edit answer @LeoDabus :)
there is many. you should test your code before posting
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.