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) addUIApplication.SharedApplication.ApplicationSupportsShakeToEdit = true;then put this code in your
UIViewController
subclass/es.#region respond to shaking (OS3+)Within your
public override bool CanBecomeFirstResponder {
get {
return true;
}
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
this.BecomeFirstResponder();
}
public override void ViewWillDisappear (bool animated)
{
this.ResignFirstResponder();
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...
Update();
}
}
#endregion
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);
return;
}
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).
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
ReplyDeleteHi Giuseppe, I thought that _was_ an example?
ReplyDeleteThere is a complete implementation in the iSOFlair 2.0 sample.
Thanks a lot, do you know if is there a good book to start with monotouch iphone development?
ReplyDeleteI'm not really aware of any monotouch books (yet). @wbm has tweeted that he's got an ebook in the works for WROX.
ReplyDelete