Download the file... - Wiley

secrettownpanamanianΚινητά – Ασύρματες Τεχνολογίες

10 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

136 εμφανίσεις

Available Now!

Professional iPhone
Programming with
MonoTouch and .NET/C#


Contents
iPhone Requirements
2
Development Strategies
3
Web Development with AS
P
.NET
3
MonoDevelop and MonoTouch
4
Visual Studio .NET

MonoDevelop
4
Classes in MonoTouch
4
What Is MonoTouch?
4
Namespaces and Classes
5
Introduction to Development on the Mac with MonoDevelop
6
Interface Builder
8
Outlets 1
0
Actions 1
4
Deploying to an iPhone 1
5
Mapping 1
7
MKMapView 1
7
The Application 1
8
Annotating the Map 2
0
Debugging 2
1
Interacting with Other Applications 2
2
UIPicker 2
2
NSUrl 2
4
UIAlertView 2
6
UITableView 2
6
DataSource 2
7
Binding Data to a UITableView 2
9
Customizing UITableView 3
0
Accelerometer 3
3
Settings 3
4
Things to Watch Out For 3
7
Resources Used 3
8
About Wallace B. McClure 3
9
Building iPhone and iPod
touch Applications for the

.NET/C
# Developer with
MonoTouch
The iPhone by Apple has taken the mobile world by storm since its original release in 2007. At

that point in time, the only way to target the iPhone was by either writing a web application or
jailbreaking the iPhone. Neither were very good options. Writing a web application for the iPhone
is not difficult, but it doesn’t take advantage of the native capabilities of the device. Jailbreaking an
iPhone relies on the owner of the device to install a piece of software that sidesteps the iPhone’s
security schemes and official distribution mechanisms. There are several issues with jailbreaking:
Jailbreaking requires the iPhone’s owner to perform the operation. Many iPhone users are
not technically proficient enough to do this.
The legality of jailbreaking is unclear. It is not clear where jailbreaking falls within the
Digital Millennium Copyright Act.
There are a series of unknowns with jailbreaking. How well can an iPhone that has been
jailbreaked be upgraded to new versions of the iPhone OS? Will jailbreaking an iPhone
open it up to security issues?
In 2008, Apple released the ability to run applications directly on the iPhone and introduced the
App Store. With the ability to run applications directly on the iPhone comes the possibility of a
development ecosystem that can target the capabilities of the device. These capabilities include
amazing graphics, sound, and other features that are revolutionary in a mobile device. With the
App Store, Apple has provided a single location for users to find applications that take advantage of
features that are natively available on the iPhone. The iPhone is the leader of the smartphone pack
in terms of integrating phone, apps, web, and music support in one consumer-friendly package.



Building iPhone and iPod touch Applications

.NET developers are the largest set of developers in the general software development ecosystem. .NET
developers, who primarily work with Microsoft technologies, have looked at iPhone with a high degree
of envy. There are many stories about developers working a relatively short amount of time, submitting
an application to the App Store, and making hundreds of thousands of dollars quickly. A recent report by
the IT market research company Yankee Group states that sales of smartphone applications will increase
to $4.3 billion in 2013 from $343 million in 2009.
In the summer of 2009, Novell announced a version of Mono that is designed to run within the iPhone as
a native application. This version of Mono, called
MonoTouch,
generated significant excitement within
the .NET community. MonoTouch allows .NET developers to take a portion of their existing
development knowledge and use that to build applications that run on the iPhone. Although you can’t
take an existing .NET application and run that application on the iPhone, a developer can apply his or
her knowledge to building an iPhone application. I liken it to an American Southerner going to England
and speaking the British dialect. You know the same basic language, but the accents, customs, and
mannerisms are different.
When building a MonoTouch application for the iPhone, you will need a different set of tools:
Apple Macintosh
— It’s not a big surprise that you will need to have a Mac running at least

OS X 10.5.7.
iPhone SDK
— MonoTouch requires the Apple iPhone SDK. The iPhone SDK contains the
iPhone emulator, which allows an application to be tested without having to be deployed to

the device.
Mono Framework
— The Mono Framework is required. The Mono Framework is an

open framework. It is an implementation of .NET that is guided by Novell and hosted at
http://mono-project.com
MonoTouch Framework
— MonoTouch is a .NET layer over many of the iPhone features. It is
licensed by Novell. Unfortunately, at the time of this writing, MonoTouch requires a separate
purchase. The MonoTouch Framework is available at
http://monotouch.net
MonoDevelop
— MonoDevelop is the standard tool for developing with Mono and
MonoTouch. MonoDevelop is the tool that this Wrox Blox will use for developing with
MonoTouch. MonoDevelop is available at
http://monodevelop.com
Xcode
— Xcode is Apple’s development tool. It has several good features designed for writing
code that targets the iPhone. This Wrox Blox does not directly use Xcode, but Xcode comes with
several tools that you can use with MonoDevelop to debug against the iPhone.
iPhone Requirements
Developing on the iPhone requires that the developer submit to two important requirements. These
requirements are that the iPhone does not support Just-In-Time (JIT) compilation and the developer
must agree not to use any scripting engines or JIT capabilities. The lack of support for JIT compilation
occurs at the iPhone kernel level and is a technical limitation of the iPhone. This is a problem for .NET
development. With .NET development, source code (VB, C#, or other languages) is compiled to
Microsoft Intermediate Language (MSIL). Once the executable is set to run on an actual system, the JIT
process occurs, which compiles the MSIL code into actual code that takes advantage of the hardware the
code is running on. Unfortunately, this is not allowed in the iPhone. The iPhone developer is not allowed






Building iPhone and iPod touch Applications

to use scripting engines or JIT technology because of legal issues. As developers almost certainly know,
Apple is not shy about protecting its legal agreements.
MonoTouch meets these two requirements by being a static compiler. MonoTouch emits executables that
run as native applications. There is no JIT or scripting involved, so the contractual and technical
requirements are met for running on the iPhone. MonoTouch does this by using the Mono Project’s
Ahead of Time (AOT) compilation feature, which is beyond this general discussion.
MonoTouch does have a few limitations. MonoTouch has no ability to do code generation at run

time.
System.Reflection.Emit
is not available. No support for
System.Runtime.Remoting
is

allowed. There is no support for any type of language built on the Dynamic Language Runtime.

There is no support for creating types dynamically. MonoTouch’s Ahead of Time (AOT) support

will cause limited support for generics. There are several other limitations that are listed at

http://monotouch.net/Documentation/Limitations
Development Strategies
For .NET developers, there are several strategies for building an application for the iPhone. This section
covers three strategies and how developers can get an application working on the iPhone.
Web Development with ASP.NET
The iPhone comes with the Safari web browser. With the update to the iPhone 3.x operating system,
iPhone users now have a mobile version of the Safari Version 4 browser. Many .NET developers are
working in ASP.NET. It is possible to build a web-based application in ASP.NET that directly targets the
iPhone web browser. There are pros and cons to this strategy.
The major pro to building an ASP.NET application that directly targets the iPhone is the deployment of
new versions of the application. New versions of the application are directly available to iPhone users
the moment the deployment is made to a web server. There is no need to wait for an application to be
accepted by the App Store and for users to download the application. While it currently takes two weeks
from the time an application is sent to the App Store until the time it is accepted and deployed, the App
Store can be bypassed and a web application can made available to users. Developers are able to stay in
their existing development environments and use the tools that they are the most familiar with.
The major con to building an ASP.NET application is that the application will have limited support for
taking advantage of the native features of the application. When a user somehow loses connection,
whether it’s a bad connection over the 3G network or a lost Wi-Fi connection, the user is unable to load
the application. The safari browser in the iPhone does have offline support in the browser; however, if the
application does not take advantage of the offline features in the browser, then the user is out of luck.
There are several levels to creating an ASP.NET application that targets the iPhone. At the basic
compatible level, a web application will be compatible with Safari on the iPhone. The next level is a

web-optimized application to target Safari on the iPhone. An optimized application will be one that
realizes it is running on Safari and then will take advantage of Safari when the browser is detected.
Finally, a developer can build a web application that specifically targets Safari on the iPhone. This will
take advantage of the Safari web browser running on the iPhone; however, it will also require the most
development time of the options for ASP.NET web developers.
Building iPhone and iPod touch Applications

MonoDevelop and MonoTouch
When using MonoTouch, MonoDevelop on the Mac will be the primary tool that developers use. It
allows developers to build native applications that run on the iPhone. Building an application in
MonoDevelop allows existing developers to apply their .NET development knowledge to building a
native application for the iPhone.
Visual Studio .NET

MonoDevelop
There is no getting around the requirement of having a Mac with the iPhone SDK to deploy an
application to the iPhone. As a result, the .NET developer must leave behind the Visual Studio
development platform at some point. A strategy for MonoTouch development is for developers to use
Visual Studio for creating the non-user-interface (non-UI) portion of their application, debug in Visual
Studio, and then use that code in their MonoTouch application. This strategy works well for reusing
existing logic. This logic can be encapsulated into classes that can be carried over to MonoDevelop,
recompiled, and deployed to the iPhone. There are several ways to handle this:
A Windows machine with Visual Studio can be used to host Visual Studio. This machine can be
used to develop certain basic pieces of code. That code can then be moved to a Mac running
MonoDevelop and MonoTouch and can be used within the MonoDevelop/MonoTouch
application.
Visual Studio can be hosted within a vmware style guest session and the code could be moved
into the host running MonoDevelop/MonoTouch.
The only problem with this approach is that there is a danger of implementing some code that is
available in Microsoft .NET but not available on the MonoTouch platform.
Classes in MonoTouch
This section takes a look at the general set of classes and features available in MonoTouch.
What Is MonoTouch?
Overall, the MonoTouch Application Programming Interface (API) is a combination of the .NET 3.5
Framework’s core features and the APIs on the iPhone. MonoTouch provides a bridge (
interop
) between
the iPhone’s native APIs based on Objective-C and C-based APIs to the .NET world that C# developers
are accustomed to.
MonoTouch is made up of the following four components:
The Monotouch.dll is a C# assembly that provides a binding API into the iPhone’s native APIs.
These native APIs supported include Quartz, Core Animation, and the other APIs of the iPhone.
A command-line SDK that will compile C# and Common Intermediate Language (CIL) code.
This compiled code can then be run in the simulator or an actual iPhone.




Building iPhone and iPod touch Applications

An add-in to MonoDevelop that allows for iPhone development and allows for the Interface
Builder to be used to create graphical applications.
A commercial license of the Mono run time. A commercial license allows for the static linking of
the Mono run time with the code developed.
Namespaces and Classes
MonoTouch provides a rich set of namespaces and classes to support building applications for the
iPhone. The most popular namespaces and classes are:
MonoTouch.ObjCRuntime
— This namespace provides the interop/bridge between the

.NET/C# world and the Objective-C world of the iPhone.
MonoTouch.Foundation
— This namespace provides support for the data types necessary to
communicate with the Objective-C world of the iPhone. Most types are directly mapped. For
example, the
NSObject ObjectiveC
base class is mapped to the
MonoTouch.Foundation

.NSObject
class in C#. Some classes are not directly mapped and are instead mapped to their
native .NET types. For example,
NSString
maps to the basic string type and
NSArray
maps to a
strongly typed array.
MonoTouch.UIKit
— This namespace provides a direct mapping between the UI components
within Cocoa Touch. The mapping is done by providing .NET classes for each UI component.
This is the namespace that developers will spend most of their time working with. For .NET
developers, Cocoa Touch is an abstraction layer orAPI for building programs that run in the
iPhone. Cocoa Touch is based on the Cocoa API used in building programs that run on the Mac
OS X operating system. Cocoa Touch can be thought of as Cocoa tuned for the touch-based
iPhone operating system.
OpenTK
— This namespace is a modified version of the
OpenTK
API.
OpenTK
is an object-
oriented binding for
OpenGL
.
OpenGL
stands for the “Open Graphics Library.”
OpenGL
is an API
for using three-dimensional graphics.
OpenTK
is a library for performing
OpenGL
,
OpenAL
, and
OpenCL
. It is written in C# and runs on Windows, Mac OS X, and Linux. The
OpenTK

implementation on the iPhone has been updated to use CoreGraphics and to only expose the
functionality available on the iPhone.
In addition, MonoTouch provides a set of additional namespaces that may be important to you and
should be mentioned. These namespaces are
MonoTouch.AddressBook
MonoTouch.CoreGraphics
MonoTouch.AddressBookUI
MonoTouch.MapKit
MonoTouch.AudioToolbox
MonoTouch.MediaPlayer
MonoTouch.AVFoundation
MonoTouch.MediaPlayer
MonoTouch.CoreAnimation
MonoTouch.SystemConfiguration
These namespaces are fairly self-explanatory regarding what functionalities they perform, which are
specific to interacting directly with other applications on the iPhone.






Building iPhone and iPod touch Applications

Introduction to Development on the Mac
with MonoDevelop
You’ll start by building an application with MonoDevelop, running it in the iPhone simulator, and finally
deploying that application to an iPhone. MonoDevelop is the software development tool for Mono on
the Mac. MonoDevelop is available for Windows, Mac, and several flavors of Linux; however, we will
concentrate on MonoDevelop for the Mac. MonoDevelop for the Mac is a new product. It is officially
released with MonoDevelop 2.2. MonoDevelop is an Integrated Development Environment (IDE) for
developing with Mono/.NET, C#, and other languages. MonoDevelop can be used to create iPhone
applications, desktop applications, and web applications with WebForms and MVC.
The first thing that a developer will do is to start up MonoDevelop (
Figure 1
). Given that this is most
likely the first time a developer has gone through this, this section explains it in excruciating detail.
Hopefully, this will help with any questions that may arise. Once MonoDevelop is running, create an
iPhone application. This can be done by selecting File

New

Solution and selecting an iPhone
application to create, as shown in
Figure 2
.
Figure 1
Building iPhone and iPod touch Applications

Now that a solution has been created, the solution will by default appear on the left-hand side of
MonoDevelop. The solution will appear similar to the solution in
Figure 3
.
Figure 
Figure 
The solution is visible, along with:
The Specific Project
— The project in this case is OpenUrl, which is one of the examples seen
later in the Wrox Blox.
References
— The references are a list of the namespaces that are included in this project.
Although MonoTouch comes with a set of standard references, some namespaces may need to
be added, such as
Linq
.
Main.cs
— This is the default startup template used by MonoTouch. It has the
Main()
method.
The
Main()
method is the starting point for an iPhone application. It also starts the application’s
event loop for handling interaction between the iPhone and the application.
MainWindow.xib
— This file defines the user interface for an application. This file is typically
modified in Interface Builder. Interface Builder has some slightly different concepts that are
explored in the following section.




Building iPhone and iPod touch Applications

MainWindows.xib.designer.cs
— This file contains definitions of the views, controls, outlets,
and actions that exist within the user interface. This file is updated each time that the user
interface is updated through Interface Builder. It should not be updated manually.
Other files
— There are several additional files that may be included in the project. In this
example project, there is a file called ProtocolData.cs, which is a class file included in this project.
Interface Builder
Interface Builder (IB) is the tool that developers will use to create the interface for their application.
When IB starts up, a blank surface will be displayed. On the blank surface, developers can drag controls
from the Library onto the design surface. Once the controls are on the design surface, they can be
arranged to create the necessary user interface. In
Figure 4
, the design surface of IB is shown.


Figure 
With IB, the controls are dragged from the Library and placed on the Window design surface. For Visual
Studio developers, this is a familiar concept.
Building iPhone and iPod touch Applications

The controls built into MonoTouch fall into four basic areas. These areas and controls are:
Controllers
— The Controllers are a family of controllers that control some type of activity.
Data Views
— The Data Views typically present some type of information to the user. The
controls presented are:
q
Table View
— A Table View will present data to a user. Users are able to scroll through the
data. Typically, a single cell in a table view is an entire row.
q
Table View Cell
— The Table View Cell allows for attributes and behaviors of cells to be
defined and applied within a table view.
q
Image View
— The Image View displays an image or animation to a user. In the case of an
animation, this is defined as an array of images.
q
Web View
— The Web View displays web content to a user within an application.
q
Map View
— The Map View displays map content to a user within an application.
q
Text View
— The Text View displays multiple lines of editable text.
q
Scroll View
— The Scroll View provides a way for content to be displayed that does not
entirely fit within a single window view.
q
Picker View
— The Picker View displays a slot-machine-style spinning wheel. For .NET
developers new to MonoTouch, this control is similar in concept to a dropdown list box.
Unfortunately, the picker view does not look like a dropdown list box.
q
Date Picker
— The Date Picker is a set of rotating wheels that allow for dates and times to
be selected.
Inputs & Values
— The Inputs & Values provide a set of UI widgets that are designed for user
input. These widgets are:
q
Segmented Control
— The Segmented Control can be thought of a button where different
segments/parts of the button function as individual controls.
q
Label
— The Label is a control to display text.
q
Round Rect Button
— The Round Rect Button control implements touch events. This is
equivalent to a button in .NET.
q
Text Field
— The Text Field control allows for users to add text or data through the virtual
keyboard.
q
Switch
— The Switch Control allows users to toggle values in a user interface. Conceptu
-
ally, this control is similar to a checkbox.
q
Slider
— The Slider Control allows users to input a single value from a range of values.
q
Progress View
— The Progress View control allows for the display of the progress of a
running task. Typically, the Progress View is used for long-running tasks to provide feed
-
back to the user.



Building iPhone and iPod touch Applications
10
q
Activity Indicator View
— The Activity Indicator View control provides feedback that a
task is currently running. There is no indication of the state of the task, merely one that the
task is running.
q
Page Control
— The Page Control provides the user with information that there are

additional open pages in the application.
Windows, Views & Bars
:
q
Window
— Windows define and are displayed on screen.
q
View
— The View Control is a rectangular region for drawing and handling events.
q
Search Bar
— The Search Bar Control is a text field with round edges and a search icon. Its
UI look is designed to show the user that the field will be used for searching.
q
Search Bar and Search Display Controller
— The Search Bar and Search Display

Controllers are the Search Bar control, Bookmark button, Cancel button, and a Table View
that displays the results of a search.
q
Navigation Bar
— The Navigation Bar is a UI control that supports navigation of content
in a hierarchical way.
q
Navigation Item
— The Navigation Item Control contains information about a navigation
item contained within a Navigation Bar.
q
Toolbar
— The Toolbar Control displays a toolbar at the bottom of the screen. It supports
toolbar items within the toolbar.
q
Bar Button Item
— The Bar Button Item Control represents an item within a Toolbar

control or Navigation Bar.
q
Flexible Space Bar Button
— The Flexible Space Bar Button Control represents the amount
of space within a toolbar.
q
Tab Bar
— The Tab Bar Control allows for a tab bar to be displayed at the bottom of the
screen. The Tab Bar Control allows for the selection of tab bar items.
q
Tab Bar Item
— The Tab Bar Item Control is an item within a Tab Bar Control.
Outlets
One of the most confusing things for a developer first learning about MonoTouch and the iPhone is an
outlet
. This term is used throughout the Apple developer site as well as the MonoTouch site. An outlet is
a private pointer to a UI object and is only visible within the class in which it is defined.
Once the controls have been placed on the design surface, the controls will need to have their outlets
defined in the application delegate. The outlets are created by clicking on the plus (+) button in the

Class Outlets section of the App Delegate Identity window. This can be seen in
Figure 5
, where the
outlets are created.

Building iPhone and iPod touch Applications
11
Now that the outlets exist, the developer needs to go to the Connections tab in the Inspector. From there,
the Outlets need to be wired up to the App Delegate. This is shown in
Figure 6
, where the developer will
create a connection from the Outlet to the UI element. The connection is created by selecting the circle to
the right of the Outlet listed in the App Delegate Connection and dragging that connection to the control
on the design surface.
Figure 
Building iPhone and iPod touch Applications
1
Finally, the App Delegate Connections should appear like
Figure 7
.
Figure 
Figure 
The following code makes up the MainWindow.designer.xib.cs file. There are a couple of interesting
items of note in the code:
A partial class is created. The partial class
AppDelegate
allows the contents of this file to be
compiled with the content of the
AppDelegate
partial class as defined in the Main.cs file.
The connections as defined are private. As a result, if they needed to be made available to
another class, connections to the class would need to be defined.


Building iPhone and iPod touch Applications
1
namespace OpenUrl {
// Base type probably should be MonoTouch.Foundation.NSObject or subclass
[MonoTouch.Foundation.Register(“AppDelegate”)]
public partial class AppDelegate {
[MonoTouch.Foundation.Connect(“window”)]
private MonoTouch.UIKit.UIWindow window {
get {
return ((MonoTouch.UIKit.UIWindow)(this.GetNativeField(“window”)));
}
set {
this.SetNativeField(“window”, value);
}
}
[MonoTouch.Foundation.Connect(“SubmitCall”)]
private MonoTouch.UIKit.UIButton SubmitCall {
get {
return ((MonoTouch.UIKit.UIButton)(this.GetNativeField(“SubmitCall”)));
}
set {
this.SetNativeField(“SubmitCall”, value);
}
}
[MonoTouch.Foundation.Connect(“SecondaryInformation”)]
private MonoTouch.UIKit.UITextField SecondaryInformation {
get {
return ((MonoTouch.UIKit.UITextField)
(this.GetNativeField(“SecondaryInformation”)));
}
set {
this.SetNativeField(“SecondaryInformation”, value);
}
}
[MonoTouch.Foundation.Connect(“ProtocolSelection”)]
private MonoTouch.UIKit.UIPickerView ProtocolSelection {
get {
return ((MonoTouch.UIKit.UIPickerView)
(this.GetNativeField(“ProtocolSelection”)));
}
set {
this.SetNativeField(“ProtocolSelection”, value);
}
}
[MonoTouch.Foundation.Connect(“MainInformation”)]
private MonoTouch.UIKit.UITextField MainInformation {
get {
return ((MonoTouch.UIKit.UITextField)
(this.GetNativeField(“MainInformation”)));
}
set {
this.SetNativeField(“MainInformation”, value);
}
}
}
}
Building iPhone and iPod touch Applications
1
Now that the basics of the application are set up, the developer can get down to writing the application
logic. Within the Main.cs file, there is the following code:
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its
// UI and is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();
return true;
}
public override void WillTerminate (UIApplication application)
{
base.WillTerminate (application);
}
// This method is required in iPhoneOS 3.0
public override void OnActivated (UIApplication application)
{
}
}
The
AppDelegate
class is a partial class. This allows for it to be compiled together with the connections
as created in IB. By compiling the separate .cs file definitions together, the resulting code runs as if it
were originally from the same file. This allows for multiple programs (IB and MonoDevelop, in this case)
to have the responsibility of file and code management without the problem of them easily writing over
each other.
The
AppDelegate
class inherits from the
UIApplicationDelegate
class. The
UIApplicationDelegate
defines methods that are called by the
UIApplication
singleton that is
created by a running application.
Actions
Now that a user interface has been created, the application needs to be able to respond to user events.
For those familiar with Visual Studio, creating actions (also called handling events in the Windows
world) is a fairly easy concept. For a button in a WinForm or WebForm, double-clicking on the button
results in an event being defined in the control (WebForm) or in the Designer.cs file (WinForm), the
source file opening, and the editor taking the developer to the
click
event. The developer can then
place code within that event to perform whatever functionality is needed. There is a similar, somewhat
more manual process for doing this in MonoDevelop with MonoTouch.
Now that the UI controls are available to the developer by creating outlets, the UI controls are available
within the
AppDelegate
class. MonoDevelop allows for the handling of user events; however, this is a
manual process. Open the Main.cs file and go to the
FinishedLaunching()
method within the
AppDelegate
class. To set up the
touchdown
event on a button, which is roughly the equivalent of a
click
event on a button in WinForms, add an event to the control’s
TouchDown
property. MonoDevelop
provides IntelliSense style completion support, as shown in
Figure 8
.
Building iPhone and iPod touch Applications
1
Once the control’s event is created, the developer can build the application and deploy it to the simulator
by selecting [Command]+B to build the application or [Command]+[Enter] to compile and deploy; or by
selecting Build

Build and Run

Run on the MonoDevelop menus. Once the application is deployed
to the simulator, the developer will see something similar to
Figure 9
.
Figure 
Figure 
Deploying to an iPhone
Now that an application has been created and tested in the simulator, it’s time for the application to be
deployed and tested on an actual device. This is a fairly short process; however, it can be confusing. The
key pieces of the process are:
1.
Developers are required to be members of the Apple iPhone Developer Program. The cost of this
program at time of writing is $99 per year.
.
Request and install the Developer Certificate that is obtained from Apple through the iPhone
Developer Program membership. This Certificate should be visible within the development
Mac’s Keychain security utility.
Building iPhone and iPod touch Applications
1
.
Request and install the Deployment Certificate that is obtained from Apple through the iPhone
Developer Program membership. This Certificate should be visible within the development
Mac’s Keychain security utility.
.
The iPhone must be properly provisioned. Luckily, Apple supplies a wizard utility through its
developer web site that helps in the setup and provisioning of the iPhone.
.
Once the development system is set up, the MonoDevelop project must be set up to deploy the
application to the iPhone when the developer selects the option to deploy to the device. This is
accomplished by setting the project’s options. The developer will navigate to Project Options


Build

iPhone Bundle Signing, as seen in
Figure 10
. In this window, the developer will need to
select the identity that is used.
Figure 10
Apple has several great resources for setting up the keys and deployment setup for Mac developers. To
access these resources, you will need to be a member of the Apple iPhone Developer Program.
The iPhone Developer Program web site:
http://developer.apple.com/iphone/program
.

You will need to be logged into to view the rest of the resources.
The iPhone Developer Program’s provisioning web site
:
http://developer.apple.com/
iphone/manage/overview/index.action
.
An Apple PDF document that describes the certificate process in minute detail:
http://
developer.apple.com/iphone/download.action?path=/iphone/iphone_developer_
program_user_guide/iphone_developer_program_user_guide__standard_program_
v2.5__final.pdf
.



Building iPhone and iPod touch Applications
1
To properly deploy an application to a local machine during development, the iPhone must be running
an OS version compatible with the iPhone SDK installed on the Mac. The iPhone can run version 3.0 of
the OS, and the SDK can be version 3.1; however, the SDK cannot be version 3.0 and the directly
connected iPhone version 3.1. If the iPhone has version 3.1 and the SDK is version 3.0, the resulting
deployment will fail. To resolve this example problem, the development machine will need to be upgraded
to a more recent version of the SDK that will support the connected version of the iPhone.
Mapping
The display of points and information on a map is a natural feature in the mobile marketplace. Outside
of some niche markets, it has never had great success on the desktop. This is typically because a user’s
desktop PC is chained to a desk. However, with a mobile platform, mobile phone devices are much
easier to move around and take with a user than is a desktop PC or laptop. Over the past few years,
there has been a movement to add mapping features to mobile devices. This is a natural progression.
Users need information about the general area, and mapping is a natural way to convey that
information.
In the following example, a call is made to the Yahoo geocoding UI, a map is displayed to a user, and a
point is displayed on the map.
MKMapView
The iPhone contains the
MKMapView
class, which is an embeddable map interface. The control can be set
up on the IB design surface exactly the same as the other user controls. The application has a text field to
allow users to put in a location and a button to initiate a series of actions that will call a web service to
geocode the location, display the general area of the location, and place a point in the center of the
geocoded location.
Figure 11
shows the UI of the application in IB.
Figure 11
Building iPhone and iPod touch Applications
1
The Application
This is a fairly simple mapping application. The user will enter a location in a text box. When the user
touches the button to perform a search, the code will go to Yahoo’s geocoding API to get the latitude and
longitude for a point, the MKMapView will be centered on the returned latitude and longitude, and a
point will be placed on the map’s center.
In the following code, the map is set up first so that it can respond to user events. The user may zoom in
and out on the location. Note that the user’s location is drawn on the map by default. This may take a
significant amount of time, depending on the time it takes to determine the user’s location. This may not
be the best idea given the amount of time necessary to get the user’s location versus the 20-second limit
on startup calls for an application.
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.MapKit;
using MonoTouch.CoreLocation;

namespace Json
{
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
}

// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its
// UI and is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();

MapVw.ZoomEnabled = true;
MapVw.UserInteractionEnabled = true;
MapVw.ScrollEnabled = true;
MapVw.ShowsUserLocation = true;

btnMap.TouchDown += BtnMapTouchDown;

LocationTF.EditingDidEnd += delegate(object sender, EventArgs e) {
UITextField utf = sender as UITextField;
Console.WriteLine(“EditingDidEnd is finished.”);
utf.ResignFirstResponder();
Building iPhone and iPod touch Applications
1
};

LocationTF.Ended += delegate(object sender, EventArgs e) {
};

LocationTF.EditingDidEndOnExit += delegate(object sender, EventArgs
e) {
};

return true;
}

void BtnMapTouchDown (object sender, EventArgs e)
{
GeoCode gCode = new GeoCode();
string location = LocationTF.Text;
double lat = 0.0, lon = 0.0, radius = 0.0;
Location.ResignFirstResponder();
gCode.GetLatLon(location, ref lat, ref lon, ref radius);
Console.WriteLine(“Lat: “ + lat.ToString() + “ Lon: “ + lon.ToString());
MapVw.Region = new MKCoordinateRegion(new CLLocationCoordinate2D(lat, lon),
new MKCoordinateSpan(.5, .5));
MapVw.ZoomEnabled = true;
MapVw.UserInteractionEnabled = true;
MapVw.ScrollEnabled = true;
btnMap.TouchDown += BtnMapTouchDown;
gCode = null;
}

// This method is required in iPhoneOS 3.0
public override void OnActivated (UIApplication application)
{
}
}
}
The final setup is based on the
UITextField
called LocationTF. The LocationTF file has three events that
are set up. This may seem a little bit confusing. In the iPhone, when a user selects a
UITextField
, the
virtual keyboard pops up by default, allowing the user to type in values. The problem is how to make
the virtual keyboard go away because it does not go away by default. The keyboard slides away when
the
UITextField
’s
.ResignFirstResponder()
method is called. This method is called in the
EditingDidEvent
event.
LocationTF.EditingDidEnd += delegate(object sender, EventArgs e) {
UITextField utf = sender as UITextField;
Console.WriteLine(“EditingDidEnd is finished.”);
utf.ResignFirstResponder();
};

LocationTF.Ended += delegate(object sender, EventArgs e) {
};

LocationTF.EditingDidEndOnExit += delegate(object sender, EventArgs
e) {
};
Building iPhone and iPod touch Applications
0
One thing to notice is that there are several events associated with editing. These events are defined
because without them, the
.EditingDidEnd
event does not seem to happen. This may be a problem
with the version of MonoTouch that was being used at that time, the version of the iPhone OS used at
that time, or some other issue.
Annotating the Map
Adding points to a map is important for many applications. These points are added through an
MKAnnotation
object.
First, there is a problem with directly using the
MKAnnotation
object. The object has several properties
that need to be set, yet these properties are Read Only as defined by the iPhone OS and not directly
settable. To get around this problem, an
ObjAnnotation
object is defined that will inherit from the
MKAnnotation
object. With this file, the object’s constructor takes in the necessary parameters to allow
code to set these values. The getters are then overridden so that the new values are output. The final step
in the code is to add the
ObjAnnotation
object through the
.AddAnnotationObject()
method.
The MKAnnotation object is defined as a protocol. In the iPhone world, a protocol is roughly

equivalent to the cross between an interface that a developer must implement and an abstract class

that is inherited from.
The class file for adding points to the map is shown next. The basic idea is to create a class that inherits
from an
MKAnnotation
object and create a constructor that allows for the input of the location, title, and
subtitle values. These values are then available through the overridden properties that are exposed.
using System;
using MonoTouch.UIKit;
using MonoTouch.MapKit;
using MonoTouch.CoreLocation;
namespace Json
{
// concept borrowed from Craig Dunn’s blog.
public class ObjAnnotation : MKAnnotation {

private CLLocationCoordinate2D _coordinate;
private string _title, _subtitle;
//getters must be overridden to return necessary data.
public override CLLocationCoordinate2D Coordinate {
get { return _coordinate; }
}
//title and subtitle are readonly, thus no setter.
public override string Title {
get { return _title; }
}
public override string Subtitle {
get { return _subtitle; }
}
/// <summary>
/// Need this constructor to set the fields, since the public
/// interface of this class is all READ-ONLY
/// <summary>
Building iPhone and iPod touch Applications
1
public ObjAnnotation (CLLocationCoordinate2D Coordinate,
string Title, string SubTitle) : base()
{
_coordinate=Coordinate;
_title=Title;
_subtitle=SubTitle;
}
}

}
Figure 12
shows the application running in the iPhone with the map and a point on the map.
Figure 1
Debugging
One question that will come up for developers familiar with Visual Studio is how to debug an
application written in MonoTouch before version 1.2. With the simulator, the application can send
information back to MonoDevelop through calls to
Console.WriteLine()
.
Figure 13
shows how
MonoDevelop will display this debugging information to the developer.
Figure 1
Building iPhone and iPod touch Applications

Starting with the release of MonoTouch 1.2, developers will be able to set break points in MonoDevelop
and step through debug code running in the simulator and an iPhone running over the same Wi-Fi
network.
Figure 14
shows that MonoDevelop can be used for stepping through code.
Figure 1
Interacting with Other Applications
The iPhone operating system allows for applications to call each other and start up an instance of the
application. This feature is provided by the
NSUrl()
method.
UIPicker
Given that there is a limited set of schemes and protocols that are supported in an iPhone, it makes sense
to present a limited set of data to the user for selection. For those familiar with the Windows operating
system and .NET, some type of dropdown list control would be used. The iPhone operating system does
not contain a control that looks like that control. The closest control is the UIPicker control, which is
shown in
Figure 15
.
Figure 1
The UIPicker is visually different, but there are also several programmatic differences:
Databinding
— .NET controls typically have a
.DataSource
property that can be used to bind
data with a control and ultimately to display it in the control. Another option is to add elements
to a control individually. With the UIPicker control in the iPhone; the
.ServiceModel
property
accepts data.
Columns
— Listboxes have either a display item or a display item and associated value. The
UIPicker control has multiple display columns. Column information is embedded within a data
source object. MonoTouch refers to the columns as
components
.
Data Source
— The data source is different from what one sees in .NET. .NET data sources are
typically data tables or some type of generic list of objects. In MonoTouch, the
UIPickerViewModel
is a class that is inherited from the
UIPickerviewModel
that has several
methods that must be overridden. These methods are:



Building iPhone and iPod touch Applications

q
GetComponentCount(UIPickerView)
— This method returns the number of columns
that will be displayed by the UIPickerView control.
q
GetComponentWidth(UIPickerView, int)
— This method returns the width of the

column requested.
q
GetRowHeight(UIPickerView, int)
— This method returns the height that will be set
on a row.
q
GetTitle(UIPickerView, int, int)
— This method will return the value displayed
in a row and column.
q
Selected(UIPickerView, int, int)
— This method returns the row that is selected
by the user.
The following code shows the data source of the UIPicker:
using System;
using MonoTouch;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace OpenUrl
{


public class ProtocolData : UIPickerViewModel
{

public static string[] protocols = new string[]
{
“http://”, “tel:”,”http://maps.google.com/maps?q=”, “sms:”,
“mailto:”
};
public string[] protocolNames = new string[]
{
“Web”, “Phone Call”, “Google Maps”, “SMS”, “Email”
};
AppDelegate ad;
public ProtocolData(AppDelegate pad){
ad = pad;
}
public override int GetComponentCount(UIPickerView uipv)
{
return(1);
}
public override int GetRowsInComponent( UIPickerView uipv, int comp)
{
//each component has its own count.
int rows = protocols.Length;
return(rows);
}
public override string GetTitle(UIPickerView uipv, int row, int comp)
{
Building iPhone and iPod touch Applications

//each component would get its own title.
string output = protocolNames[row];
return(output);
}
public override void Selected(UIPickerView uipv, int row, int comp)
{
ad.SelectedRow = row;
}
public override float GetComponentWidth(UIPickerView uipv, int comp){
return(300f);
}
public override float GetRowHeight(UIPickerView uipv, int comp){
return(40f);
}
}
}
NSUrl
The
NSUrl
class is what allows an application to open other applications within the iPhone OS while
passing parameters. The calling sequence is fairly simple. There are two steps to making this call:
1.
When the
NSUrl
class is instantiated, a string representing the URL scheme is called. Note that
different applications will have different schemes and use different protocols.
.
The static method
UIApplication.SharedApplication.OpenUrl(ns)
is called, where
ns
is
the
NSUrl
class. When the static method is called, if it is not possible to open a URL, a
false


is returned. If it is possible to open the URL that is passed, the URL is opened and a
true
is
returned. (See
Figure 16
.)
Figure 1
Building iPhone and iPod touch Applications

The following code is a short example application on how to create the
NSUrl
class and call the
OpenUrl()
method. This code demonstrates the following basic steps:
How to bind data into a UIPicker by settings its
.Model
property.
How to create an
NSUrl
object.
How to open the
NSUrl
object.
How to call the
UIAlert
object to require immediate feedback from the user.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its
// UI and is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();
ProtocolData protocolDataSource = new ProtocolData(this);
ProtocolSelection.Model = protocolDataSource;
SubmitCall.TouchDown += SubmitCallTouchDown;
MainInformation.EditingDidEndOnExit += delegate {
MainInformation.ResignFirstResponder();
};
SecondaryInformation.EditingDidEndOnExit += delegate {
SecondaryInformation.ResignFirstResponder();
};
return true;
}
public override void WillTerminate (UIApplication application)
{
base.WillTerminate (application);
}
void SubmitCallTouchDown (object sender, EventArgs e)
{
string first = MainInformation.Text;
string sec = SecondaryInformation.Text;
string prot = ProtocolData.protocols[selRow];
NSUrl ns = new NSUrl(prot + first + sec.Trim());
if (!UIApplication.SharedApplication.OpenUrl(ns))
{
var av = new UIAlertView(“Badness happened”
, “The scheme ‘” + prot + “’ is not supported on this device.”,
null, “Ok thanks”, null);
av.Show();
}
}
private int selRow = 0;
public int SelectedRow{ get {return selRow;}
set{
Console.WriteLine(“Row Selected: “ + value.ToString());
selRow = value; } }

// This method is required in iPhoneOS 3.0




Building iPhone and iPod touch Applications

public override void OnActivated (UIApplication application)
{
}
}
There are additional protocols and schemes supported in the iPhone OS. For a list of the URL schemes,
check out
http://wiki.akosma.com/IPhone_URL_Schemes
and similar sites online.
UIAlertView
There are times when the user needs to be presented with some information or question. MonoTouch has
a
UIAlertView
object. The
UIAlertView
is instantiated with a set of parameters. On the object instance,
the
.Show()
method is called. For .NET developers, this is similar in concept to the .NET MessageBox.
For JavaScript developers, this is similar to the
window.alert()
and
window.confirm()
methods.
Figure 17
shows the output of a
UIAlertView
call.
Figure 1
UITableView
One of the standard functions that applications do is display groups of data to users. With MonoTouch,
this is accomplished by the UITableView control.
In the following example, a user will put in a search term in the UITextView. A Representational State
Transfer, or REST, call is then made through the Twitter Search API. The results of the call to Twitter
Building iPhone and iPod touch Applications

Search are put into a series of objects through LINQ to XML. The resulting objects are then going to be
bound against the UITableView.
DataSource
The UITableView is similar to the UIPicker control. The data source that will be bound to the control has
its own requirements. The data source that will be bound inherits from UITableViewDataSource. There
are two methods that the data source must implement:
GetCell()
— The
GetCell
method creates an instance of UITableViewCell for the data row
that is being bound.
RowsInSelection()
— The
RowsInSelection
method returns the total number of records
that will be bound to the UITableView.
The following code shows the class that calls the Twitter Search API, gets the data back, uses LINQ to
XML to put the data into a set of objects, and stores the data in an array of results called
SearchTwitterResult array.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using MonoTouch;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace UITableView
{
public class TwitterSearch : UITableViewDataSource
{
private SearchTwitterResult[] str;

public TwitterSearch (string SearchTerm)
{
SearchByTerm(SearchTerm);
}
public void SearchByTerm(string SearchTerm)
{
string strUrl = “http://search.twitter.com/search.atom?q=”;
SearchTwitterResult sr = new SearchTwitterResult();

//SearchTwitterResult str;
List<SearchTwitterResult> strl = new List<SearchTwitterResult>();
if ((!String.IsNullOrEmpty(SearchTerm)))
{
strUrl += SearchTerm;
Console.WriteLine(“Url: “ + strUrl);
XDocument xdoc = XDocument.Load(strUrl);
Console.WriteLine(“Document Loaded.”);
XNamespace atomNS = “http://www.w3.org/2005/Atom”;
XNamespace google = “http://base.google.com/ns/1.0”;
var query = (from tweet in xdoc.Descendants(atomNS + “entry”)


Building iPhone and iPod touch Applications

where tweet != null
select new SearchTwitterResult
{
TwitterUri = tweet.Element(atomNS +
“author”).Element(atomNS + “uri”).Value,
TwitterName = tweet.Element(atomNS +
“author”).Element(atomNS + “name”).Value,
StatusDate = Convert.ToDateTime(tweet.Element(atomNS +
“updated”).Value),
Status = tweet.Element(atomNS + “title”).Value,
});
Console.WriteLine(“Query formed.”);
strl = query.ToList();
Console.WriteLine(“Query Completed.”);
Console.WriteLine(“Records stored: “ + strl.Count);
}
str = strl.ToArray();
}

public override UITableViewCell GetCell (MonoTouch.UIKit.UITableView tableView,
MonoTouch.Foundation.NSIndexPath indexPath)
{
string cellid = “cellid”;
UITableViewCell cell = tableView.DequeueReusableCell(cellid);
if ( cell == null ){
cell = new UITableViewCell(UITableViewCellStyle.Default, cellid);
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;

}
Console.WriteLine(“Current Row: “ + indexPath.Row.ToString());
cell.TextLabel.Text = str[indexPath.Row].Status;

return(cell);
}
public override int RowsInSection
(MonoTouch.UIKit.UITableView tableview, int section)
{
return(str.Length);
}
}

public class SearchTwitterResult
{
public string TwitterName { get; set; }
public string TwitterUri { get; set; }
public string Location { get; set; }
public string Status { get; set; }
public DateTime StatusDate { get; set; }
public int StatusID { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
}
Building iPhone and iPod touch Applications

From the preceding code, the search can be done through the object’s initialization or by calling the
TwitterSearch()
method. This was done for possible programming convenience, but is not a
requirement.
Included with the code is the class definition (
SearchTwitterResult
) used to hold data.
Binding Data to a UITableView
The
FinishedLaunching()
code is fairly simple. In .NET, data is typically bound by setting the
.DataSource
property. In ASP.NET, there is an additional step of calling the
.DataBind()
method. The
data binding against the UITableView is similar in concept. Data is found by setting the
.DataSource

property.
I found that calling the
.ReloadData()
method was required or the data did not bind. This may have
been due to programmer error, a bug in that build of MonoTouch, or a change in the iPhone OS.
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its
// UI and is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);

window.MakeKeyAndVisible ();
SearchButton.TouchDown += SearchButtonTouchDown;
SearchText.EditingDidEndOnExit += delegate {
SearchText.ResignFirstResponder();
};
return true;
}

void SearchButtonTouchDown (object sender, EventArgs e)
{
string SearchTerm = SearchText.Text;
TwitterSearch ts = new TwitterSearch(SearchTerm);
SearchResults.DataSource = ts;
SearchResults.ReloadData();
}

// This method is required in iPhoneOS 3.0
public override void OnActivated (UIApplication application)
{
}
}
Figure 18
shows the output of the data binding in the iPhone simulator.
Building iPhone and iPod touch Applications
0
Customizing UITableView
You have bound some code into a UITableView. The next step is to customize the layout of the
UITableView. Data outputs almost need to be customized to meet the criteria of the application. You’re
going to take the existing databinding application and modify the data display to look like
Figure 19
. In
the following example, the application is modified to take the data that is displayed within three labels.
Figure 1
Figure 1
To customize the UITableView, there are several steps that will need to be completed. First, create a new
IB file set. In this IB file set, there is a .cs file, which you can edit, and a designer.cs, which you should not
edit, along with the TCController.xib file. In this example, you’re going to add some other label controls
and populate them to simulate a grid of data one would see in an ASP.NET GridView.
Building iPhone and iPod touch Applications
1
Open up the TCController.xib file in IB. You’re going to create a UITableViewCell by placing it on the
design surface as shown in
Figure 20
.
Figure 0
The IB should look like
Figure 21
, where the File’s Owner, First Responder, and Table View Cell are
defined.
Figure 1
The outlets that are defined for a TableViewCell, called bindingCell, are a label named lblDate, a label
named lblPerson, and a label named lblStatus. The outlets are exposed to the TCController.cs file. The
outlets that are defined should look like
Figure 22
.
Figure 
Building iPhone and iPod touch Applications

The next step in the process is to modify the TCController.cs file. This file contains a partial class that
developers are allowed to modify. In the class, you have added a getter/setter combination that will
allow an external class to access the labels in the UITableViewCell. The following code shows these
modifications.
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace UITableView
{
public partial class TCController : UIViewController
{
#region Constructors

// The IntPtr and NSCoder constructors are required
// for controllers that needto be able to be created
// from a xib rather than from managed code
public TCController (IntPtr handle) : base(handle)
{
Initialize ();
}
[Export(“initWithCoder:”)]
public TCController (NSCoder coder) : base(coder)
{
Initialize ();
}

public TCController () : base(“TCController”, null)
{
Initialize ();
}
void Initialize ()
{
}
#endregion
public string Person
{
get { return (lblPerson.Text); }
set { lblPerson.Text = value;
lblPerson.MinimumFontSize = 8;
lblPerson.Font = UIFont.SystemFontOfSize(8f);
}
}
public string Date
{
get { return (lblDate.Text); }
set { lblDate.Text = value;
lblDate.Font = UIFont.SystemFontOfSize(8f);
}
}
public string Status
{
Building iPhone and iPod touch Applications

get { return (lblStatus.Text); }
set { lblStatus.Text = value;
lblStatus.Font = UIFont.SystemFontOfSize(8f);
}
}
public UITableViewCell Cell
{
get { return(cell); }
}
}
}
The final step is to modify the code in the GetCell method of the TwitterSearch class to set the values in
the TCController class, which will then update the labels in the cells, and then change the values
displayed to the user. The following code calls these changes.
tcc.Date = str[indexPath.Row].StatusDate.ToString();
tcc.Person = str[indexPath.Row].TwitterName;
tcc.Status = str[indexPath.Row].Status;
Accelerometer
The Accelerometer is one of the interesting features of the iPhone. The Accelerometer allows a program
to read when the iPhone is moving and return data about the movement of the device. The iPhone OS
and MonoTouch provide a software solution to integrating with the Accelerometer and handling
acceleration events. The
SharedAccelerometer
is a shared C# object that provides access to the
acceleration hardware on the device. The following code shows how to handle acceleration events and to
display that information to the user.
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its
// UI and is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();
//Acceleration does not work in the Simulator.
UIAccelerometer.SharedAccelerometer.UpdateInterval = 1 / 10;
dataLabel.Text = String.Empty;
UIAccelerometer.SharedAccelerometer.Acceleration += delegate(object sender,
UIAccelerometerEventArgs e) {
UIAcceleration acc = e.Acceleration;
double thresholdValue = 2.0;
double Velocity = Math.Sqrt(Math.Pow(acc.X, 2) +
Math.Pow(acc.Y, 2) +
Math.Pow(acc.Z, 2));
string strReturn = System.Environment.NewLine;
if ( Velocity > thresholdValue ) {
Building iPhone and iPod touch Applications

dataLabel.Text = “Velocity: “ + Velocity.ToString() + strReturn +
“ X: “ + acc.X.ToString() + strReturn +
“ Y: “ + acc.Y.ToString() + strReturn +
“ Z: “ + acc.Z.ToString();
}
};

return true;
}
A couple of notes about programming with the Accelerometer:
The Accelerometer is not available in the iPhone simulator. It can only be tested on an actual
device. In this example, all that a user would have to do is shake the device and a result is
displayed in the X, Y, Z, directions, and then total value is displayed for acceleration as defined
by the iPhone.
The setting the
UpdateInterval
directly affects the device. The more times that acceleration
events are handled, the more the battery on the device is drained.
The
UpdateInterval
can only be within the hardware resolution of the device. If there are
more requested updates per second than the hardware supports, the software is unable to
handle more updates per second than the hardware allows.
Settings
Applications have settings that need to be stored someplace. These are settings that rarely change but are
not appropriate to be compiled into an application. For .NET programming, developers are accustomed
to app.config and web.config files as well as the Windows Registry. The iPhone operating system allows
for the storage of settings in a special file. The file is the root.plist file. The steps to create the file and
have it work in the iPhone are:
1.
Within a project, create a folder named Settings.bundle.
.
Within the Settings.bundle folder, create a file named Root.plist, as shown in
Figure 23
.



Figure 
.
On the properties of the Root.plist file, as shown in
Figure 24
, set the Build action to “Content”
and the “Copy to output directory” to “Always copy.”
Building iPhone and iPod touch Applications

.
The next step is to create the content of the Root.plist file. Double-clicking on the file opens the
Property List Editor. For this example, the settings are shown in
Figure 25
. It is very important
that the contents of the Root.plist file are exact. If the content is not done correctly, the settings
will not be available. Unfortunately, there is no compile-time checking.
Figure 
Figure 
.
The settings are now visible.
Figure 26
shows the returning of the data and displaying it in the
application’s UI.
Figure 
.
The final step is to look at the iPhone’s settings applet. The applet displays the settings for this
application and allows the user to change those values, as shown in
Figure 27
.
Building iPhone and iPod touch Applications

The following code, which performs the lookup, is fairly simple. The
NSUserDefaults
object is set by
getting the
NSUserDefaults.StandardUserDefaults
object. The object exposes a number of methods
to get at values. This example calls the
StringForKey()
method to obtain the key’s value.
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its
// UI and is ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
NSUserDefaults pref = NSUserDefaults.StandardUserDefaults;
string User, Pwd;
window.MakeKeyAndVisible ();
User = pref.StringForKey(“UserName”);
Pwd = pref.StringForKey(“PassWord”);
UserIdtxt.Text = User;
PassWordtxt.Text = Pwd;
UserIdtxt.EditingDidEndOnExit += delegate(object sender, EventArgs e) {
UserIdtxt.ResignFirstResponder();
};
Figure 
Building iPhone and iPod touch Applications

PassWordtxt.EditingDidEndOnExit += delegate(object sender, EventArgs e) {
PassWordtxt.ResignFirstResponder();
};
return true;
}

// This method is required in iPhoneOS 3.0
public override void OnActivated (UIApplication application)
{
}
}
If there is a need to update the settings, this can be accomplished by the following code to reverse the
previous process.
NSUserDefaults pre = NSUserDefaults.StandardUserDefaults;
pre[“UserName”] = new NSString(UserIdtxt.Text);
pre[“PassWord”] = new NSString(PassWordtxt.Text);
Things to Watch Out For
There are a few things that developers need to be aware of when building their applications on the
iPhone with MonoTouch:
The iPhone has a startup timer. If an application takes longer than 20 seconds to start up, it is
killed by the iPhone OS.
The iPhone OS will kill any application that is unresponsive for longer than 20 seconds. To work
around this, you will need to perform some type of asynchronous operation.
The time spent processing the
FinishedLaunching()
event counts against the startup timer.
As a result, you will not want to do any long-term synchronous processing in the
FinishedLaunching()
event.
The iPhone simulator is good for initial testing; however, it is not necessarily accurate for all
testing. Just because something works in the simulator doesn’t mean it will run in the iPhone in
the same way. Final testing should be completed in the iPhone.
With .NET, executables are fairly small. Every application shares the .NET Framework, so the
applications don’t have their own copy of the framework. MonoTouch is not built into the
iPhone. MonoTouch applications must have their own copy of the framework. MonoTouch is
compiled into your application. The result is that MonoTouch applications are larger on disk
than a comparable .NET application.
Although MonoTouch is a commercially licensed product, it is still a product that is under
continual development. MonoTouch may not have support for a specific namespace or
assembly. There are two options for this situation:
q
Wait on the implementation of that assembly from the MonoTouch product.
q
Pull the necessary code or assembly to your project and test to get it to work.






Building iPhone and iPod touch Applications

In addition to the technical issues of building an application for the iPhone, there are also some design
issues that developers should be aware of:
Don’t design an application for a desktop environment and think that it can be scaled down to
an iPhone, or any mobile device. iPhone and mobile device applications are really good for
simple, limited-purpose functions, but they should not try to do everything that a desktop
application does.
An iPhone does not have the display, hardware, or storage of a desktop computer — don’t
design for a desktop computer.
The iPhone simulator is a fine tool, but don’t limit testing to the iPhone simulator. A simulator is
just a simulator. There is a keyboard and a mouse associated with the iPhone simulator. To really
test a complicated design, the application must be tested from a physical iPhone.
Resources Used
Craig Dunn’s blog:
http://conceptdev.blogspot.com
/
. I want to give a big thank you for
Craig’s blog. It is a great resource.
MonoTouch site:
http://monotouch.net/





Building iPhone and iPod touch Applications

About Wallace B. McClure
Wallace B. “Wally” McClure graduated from the Georgia Institute of Technology in 1990 with a Bachelor
of Science in electrical engineering. He continued his education at Georgia Tech, receiving a Master’s in
the same field in 1991.
Since that time, he’s done consulting and development for the U.S. Department of Education, Coca-Cola,
Bechtel National, Magnatron, and Lucent Technologies, among others. He’s worked with products and
services such as COM, Oracle, MySQL, DB2, and SQL Server, as well as applications in the Microsoft
.NET Framework. Wally has been working with the .NET Framework since the summer of 2000. He
specializes in building applications that have a large number of users and large amounts of data as well
as user interface specific technologies, such as AJAX and now the iPhone. He is a Microsoft MVP

and an ASPInsider, and a partner in Scalable Development, Inc. You can read Wally’s blog at

www.morewally.com
or listen to him co-host the ASP.NET Podcast at
www.aspnetpodcast.com
.
In addition, Wally travels around the southeastern United States doing user group talks and sessions at
various CodeCamps. When not working or playing with technology, Wally spends time with his wife,
Ronda, and their two children, Kirsten and Bradley.
Building iPhone® and iPod touch® Applications for the .NET/C#
Developer with MonoTouch
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
ISBN: 978-0-470-59073-7
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or
promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is
sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional
services. If professional assistance is required, the services of a competent professional person should be sought. Neither
the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is
referred to in this work as a citation and/or a potential source of further information does not mean that the author or the
publisher endorses the information the organization or Website may provide or recommendations it may make. Further,
readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this
work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks:
Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other
countries, and may not be used without written permission. iPhone and iPod touch are registered trademarks of Apple,
Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any
product or vendor mentioned in this Wrox Blox.
This PDF should be viewed with Acrobat Reader 6.0 and later, Acrobat Professional 6.0 and later, or Adobe Digital Editions.
Usage Rights for Wiley Wrox Blox. Any Wiley Wrox Blox you purchase from this site will come with certain restrictions
that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:
• Are entitled to three downloads
• Are entitled to make a backup copy of the file for your own use
• Are entitled to print the Wrox Blox for your own use
• Are entitled to make annotations and comments in the Wrox Blox file for your own use
• May not lend, sell or give the Wrox Blox to another user
• May not place the Wrox Blox file on a network or any file sharing service for use by anyone other than yourself or
allow anyone other than yourself to access it
• May not copy the Wrox Blox file other than as allowed above
• May not copy, redistribute, or modify any portion of the Wrox Blox contents in any way without prior permission
from Wiley
If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8
a.m.
- 5
p.m
. EST,
Monday - Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States
only) or 317-572-3994 (International) 8
a.m
. - 8
p.m
. EST, Monday - Friday).
Associate Publisher
Jim Minatel
Acquisitions Editor
Paul Reese
Project Editor
Kristin Vorce
Technical Editor
Jim Zimmerman
Production Editor
Rebecca Anderson
Copy Editor
Cate Caffrey
Editorial Director
Robyn B. Siesky
Editorial Manager
Mary Beth Wakefield
Marketing Manager
David Mayhew
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Proofreader
Nancy Carrasco
Available
Now!