Saturday 3 October 2009

MonoTouch shake shake shake

I like the way the iPhone Facebook application updates on a shake (no wasted screen real-estate with an Update button), so I went looking for some ideas how to do it. This StackOverflow thread about shake API describes both 'old school' (using accelerometer) and new OS3.0 built-in MotionEnded methods.

This c# code for MonoTouch just uses the OS3.0 feature - it's easier and the Simulator Hardware menu has a Shake Gesture item for testing :)

Firstly, in your Main.cs (or wherever FinishedLaunching is defined) add
UIApplication.SharedApplication.ApplicationSupportsShakeToEdit = true;
then put this code in your UIViewController subclass/es.
#region respond to shaking (OS3+)
public override bool CanBecomeFirstResponder {
get {
return true;
public override void ViewDidAppear (bool animated)
base.ViewDidAppear (animated);
public override void ViewWillDisappear (bool animated)
base.ViewWillDisappear (animated);
public override void MotionEnded (UIEventSubtype motion, UIEvent evt)
Console.WriteLine("Motion detected");
if (motion == UIEventSubtype.MotionShake)
Console.WriteLine("and was a shake");
// Do your application-specific shake response here...
Within your Update method (or whatever you call it), you probably want to wrap your internet access with code to show/hide the network indicator spinner in the status bar (NetworkActivityIndicatorVisible = true) so the user knows that something is happening. Here's a basic example:
WebClient wc = new WebClient();
Uri uri = new Uri("http://sample.corp/stuff");
byte[] bytes = null;
try {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
bytes = wc.DownloadData(uri);
catch (Exception ex) {
Console.WriteLine("Internet connection failed: " + ex.Message);
finally {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;

NOTE: other iPhone applications use the shake gesture for Undo - here's a simple NSUndoManager example (ObjectiveC, but fairly easy to follow).


  1. Hi, I'm new in IPhone development, How I can put your code in my UIViewController subclass/es, could you give me an example?Thanks

  2. Hi Giuseppe, I thought that _was_ an example?

    There is a complete implementation in the iSOFlair 2.0 sample.

  3. Thanks a lot, do you know if is there a good book to start with monotouch iphone development?

  4. I'm not really aware of any monotouch books (yet). @wbm has tweeted that he's got an ebook in the works for WROX.


Note: only a member of this blog may post a comment.