You are on page 1of 33

Hello, iOS

Introduction to iOS Development with Xamarin

Hello.iOS Quickstart
In this walkthrough well create an application that translates an alphanumeric phone number entered by the user
into a numeric phone number, and then calls that number. The final application looks like this:

Lets get started!

Requirements
iOS development with Xamarin requires:
A Mac running OS X Mountain Lion or above.
Latest version of XCode and iOS SDK installed from the App Store .
Xamarin.iOS works with any of the following setups:
Latest version of Xamarin Studio on a Mac that fits the above specifications.
Latest version of Visual Studio Professional or higher on Windows 7 or above, paired with a Mac build host
that fits the above specifications. This setup requires a Xamarin Business License or trial.
The Xamarin.iOS OSX Installation guide is available for step-by-step installation instructions
Note: Xamarin.iOS is not available for Xamarin Studio on Windows.
Before we get started, please download the [Xamarin App Icons & Launch Screens set](Resources/Xamarin App
Icons and Launch Images.zip).

Xamarin Studio Walkthrough


In this walkthrough well create an application called Phoneword that translates an alphanumeric phone number
into a numeric phone number.
1. Lets launch Xamarin Studio from the Applications folder or Spotlight to bring up the Launch screen:

In the top left, lets click New Solution... to create a new Xamarin.iOS solution:

2. From the New Solution dialog, well choose theC # > iOS > Classic API > iPhone > Single View Application
template. Let's give it the Name Phoneword_iOS, and the Solution Name Phoneword:

You can read more about the Unified API but we recommend using the Classic API for this tutorial.
3. Next, well open the MainStoryboard.storyboard file by double-clicking on it in the Solution Pad:

4. From the Toolbox (the area on the right), lets type "label" into the search bar and drag a Label onto the
design surface (the area in the center):

5. Next, grab the handles of the Dragging Controls (the circles around the control) and make the label wider:

6. With the Label selected on the design surface, use the Properties Pad to change the Title property of the
Label to "Enter a Phoneword:"

Note: You can bring up the Properties Pad or Toolbox at any time by navigating to View > Pads.
7. Next, lets search for "text field inside the Toolbox and drag a Text Field from the Toolbox onto the design
surface and place it under the Label. Adjust the width until the Text Field is the same width as the Label:

8. With the Text Field selected on the design surface, change the Text Fields Name property in the Identity
section of the Properties Pad to PhoneNumberText, and change the Title property to "1-855-XAMARIN":

9. Next, drag a Button from the Toolbox onto the design surface and place it under the Text Field. Adjust the
width so the Button is as wide as the Text Field and Label:

10. With the Button selected on the design surface, change the Name property in the Identity section of the
Properties Pad to TranslateButton. Change the Title property to "Translate":

11. Lets repeat the two steps above and drag a Button from the Toolbox onto the design surface and place it
under the first Button. Adjust the width so the Button is as wide as the first Button:

12. With the second Button selected on the design surface, well change the Name property in the Identity
section of the Properties Pad to CallButton. Well change the Title property to "Call":

Lets save our work by navigating to File > Save or by pressing + s.


13. Now, lets add some code to translate phone numbers from alphanumeric to numeric. Well add a new file
to the Project by clicking on the gray gear icon next to the Phoneword_iOS Project in the Solution Pad and
choosing Add > New File... or pressing + n:

14. In the New File dialog, select General > Empty Class and name the new file PhoneTranslator:

15. This creates a new, empty C# class for us. Remove all the template code and replace it with the following
code:
using System.Text;
using System;
namespace Core
{
public static class PhonewordTranslator
{
public static string ToNumber(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return "";
else
raw = raw.ToUpperInvariant();
var newNumber = new StringBuilder();
foreach (var c in raw)
{
if (" -0123456789".Contains(c))
newNumber.Append(c);
else {
var result = TranslateToNumber(c);
if (result != null)
newNumber.Append(result);
}
// otherwise we've skipped a non-numeric char
}
return newNumber.ToString();
}
static bool Contains (this string keyString, char c)
{

return keyString.IndexOf(c) >= 0;


}
static int? TranslateToNumber(char c)
{
if ("ABC".Contains(c))
return 2;
else if ("DEF".Contains(c))
return 3;
else if ("GHI".Contains(c))
return 4;
else if ("JKL".Contains(c))
return 5;
else if ("MNO".Contains(c))
return 6;
else if ("PQRS".Contains(c))
return 7;
else if ("TUV".Contains(c))
return 8;
else if ("WXYZ".Contains(c))
return 9;
return null;
}
}
}
Save the PhoneTranslator.cs file and close it.
16. Next were going to add code to wire up the user interface. Lets add the code to powerthe user interface
into the Phoneword_iOSViewController class. Double-click on Phoneword_iOSViewController.cs in
the Solution Pad to open it:

17. Lets begin by wiring up the TranslateButton. In the Phoneword_iOSViewController class, find the
ViewDidLoad method. We will add our button code inside ViewDidLoad, below the
base.ViewDidLoad() call:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// code goes here
}
18. Lets add code to respond to the user pressing the first button, which weve named TranslateButton.
Populate ViewDidLoad with the following code:
string translatedNumber = "";
TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
// Convert the phone number with text to a number
// using PhoneTranslator.cs
translatedNumber = Core.PhonewordTranslator.ToNumber(
PhoneNumberText.Text);
// Dismiss the keyboard if text field was tapped
PhoneNumberText.ResignFirstResponder ();
if (translatedNumber == "") {
CallButton.SetTitle ("Call", UIControlState.Normal);
CallButton.Enabled = false;
}

else {
CallButton.SetTitle ("Call " + translatedNumber, UIControlState.Normal);
CallButton.Enabled = true;
}
};
19. Next lets add code to respond to the user pressing the second button, which weve named CallButton.
Place the following code below the code for the TranslateButton:
CallButton.TouchUpInside += (object sender, EventArgs e) => {
var url = new NSUrl ("tel:" + translatedNumber);
// Use URL handler with tel: prefix to invoke Apple's Phone app,
// otherwise show an alert dialog
if (!UIApplication.SharedApplication.OpenUrl (url)) {
var av = new UIAlertView ("Not supported",
"Scheme 'tel:' is not supported on this device",
null,
"OK",
null);
av.Show ();
}
};
20. Lets save our work, and then build the application by choosing Build > Build All or pressing + B. If our
application compiles, we will get a success message at the top of the IDE:

If there are errors, we can go through the previous steps and correct any mistakes until the application
builds successfully.
21. We now have a working application and its time to add the finishing touches! We can edit the application
name and icons in the Info.plist file. Lets open Info.plist by double-clicking on it in the Solution Pad:

22. In the iOS Application Target section, lets change the Application Name to "Phoneword":

23. To set application icons and launch images, first download the Xamarin App Icons & Launch Screens set.
In the iPhone Icons section, click directly on the (57x57) icon placeholder and select the matching icon from
the Xamarin App Icons & Launch Images directory:

Lets continue filling in all six icons. Xamarin Studio will replace the placeholders with our icons:

24. Next lets set the launch images. Well assign Default.png to the standard resolution (320x480)
placeholder, Default@2x.png to the Retina (3.5-inch) placeholder, and finally Default-568h@2x.png to the
Retina (4-inch) placeholder:

The image names follow iOS naming conventions for images of different densities.
25. Finally, lets test our application in the iOS Simulator. In the top left of the IDE, choose Debug from the first
dropdown, and iPhone Retina (4-inch) > iOS 7.x from the second dropdown, and press Start (the round
button that resembles a Play button):

26. This will launch our application inside the iOS Simulator:

Phone calls are not supported in the iOS Simulator; instead, well see our alert dialog when we try to place
a call:

Visual Studio Walkthrough


In this walkthrough well create an application called Phoneword that translates an alphanumeric phone number
into a numeric phone number.

1. Lets launch Visual Studio from the Start menu:

In the top left, lets click New Solution... to create a new Xamarin.iOS solution.

2. From the New Solution dialog, well choose the Visual C# > iOS > iPhone > Single View Application
template. We'll name the Project Phoneword_iOS and the new Solution Phoneword, as illustrated below:

3. Next, well open the MainStoryboard.storyboard file by double-clicking on it in the Solution Pane:

4. From the Toolbox (the area on the left), lets type "label into the search bar and drag a Label onto the
design surface (the area in the center):

5. Next, grab the handles of the Dragging Controls (the circles around the control) and make the label wider:

6. With the Label selected on the design surface, use the Properties Pane to change the Title property of the
Label to "Enter a Phoneword:"

Note: You can bring up the Properties or Toolbox at any time by navigating to the View menu.
7. Next, lets search for "text field inside the Toolbox and drag a Text Field from the Toolbox onto the design
surface and place it under the Label. Adjust the width until the Text Field is the same width as the Label:

8. With the Text Field selected on the design surface, change the Text Fields Name property in the Identity
section of the Properties to PhoneNumberText, and change the Title property to "1-855-XAMARIN":

9. Next, drag a Button from the Toolbox onto the design surface and place it under the Text Field. Adjust the
width so the Button is as wide as the Text Field and Label:

10. With the Button selected on the design surface, change the Name property in the Identity section of the
Properties to TranslateButton. Change the Title property to "Translate":

11. Lets repeat the two steps above and drag a Button from the Toolbox onto the design surface and place it
under the first Button. Adjust the width so the Button is as wide as the first Button:

12. With the second Button selected on the design surface, well change the Name property in the Identity
section of the Properties to CallButton. Well change the Title property to "Call":

Lets save our work by navigating to File > Save or by pressing Ctrl + s.
13. Now, lets add some code to translate phone numbers from alphanumeric to numeric. Well add a new file
to the Project by right-clicking on the Phoneword_iOS Project in the Solution Explorer and choosing Add >
New File... or pressing Ctrl + n:

14. In the New File dialog, select Visual C# > Empty Class and name the new file PhoneTranslator:

15. This creates a new empty C# class for us. Remove all the template code and replace it with the following
code:
using System.Text;
using System;
namespace Core
{
public static class PhonewordTranslator

{
public static string ToNumber(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return "";
else
raw = raw.ToUpperInvariant();
var newNumber = new StringBuilder();
foreach (var c in raw)
{
if (" -0123456789".Contains(c))
newNumber.Append(c);
else {
var result = TranslateToNumber(c);
if (result != null)
newNumber.Append(result);
}
// otherwise we've skipped a non-numeric char
}
return newNumber.ToString();
}
static bool Contains (this string keyString, char c)
{
return keyString.IndexOf(c) >= 0;
}
static int? TranslateToNumber(char c)
{
if ("ABC".Contains(c))
return 2;
else if ("DEF".Contains(c))
return 3;
else if ("GHI".Contains(c))
return 4;
else if ("JKL".Contains(c))
return 5;
else if ("MNO".Contains(c))

return 6;
else if ("PQRS".Contains(c))
return 7;
else if ("TUV".Contains(c))
return 8;
else if ("WXYZ".Contains(c))
return 9;
return null;
}
}
}
Save the PhoneTranslator.cs file and close it.
16. Next were going to add code to wire up the user interface. Lets add the backing code into the
Phoneword_iOSViewController class. Double-click on Phoneword_iOSViewController.cs in the Solution
Explorer to open it:

17. Lets begin by wiring up the TranslateButton. In the Phoneword_iOSViewController class, find the
ViewDidLoad method. We will add our button code inside ViewDidLoad, below the
base.ViewDidLoad() call:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// code goes here

}
18. Lets add code to respond to the user pressing the first button, which weve named TranslateButton.
Populate ViewDidLoad with the following code:
string translatedNumber = "";
TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
// Convert the phone number with text to a number
// using PhoneTranslator.cs
translatedNumber = Core.PhonewordTranslator.ToNumber(
PhoneNumberText.Text);
// Dismiss the keyboard if text field was tapped
PhoneNumberText.ResignFirstResponder ();
if (translatedNumber == "") {
CallButton.SetTitle ("Call", UIControlState.Normal);
CallButton.Enabled = false;
}
else {
CallButton.SetTitle ("Call " + translatedNumber, UIControlState.Normal);
CallButton.Enabled = true;
}
};
19. Next lets add code to respond to the user pressing the second button, which weve named CallButton.
Place the following code below the code for the TranslateButton:
CallButton.TouchUpInside += (object sender, EventArgs e) => {
var url = new NSUrl ("tel:" + translatedNumber);
// Use URL handler with tel: prefix to invoke Apple's Phone app,
// otherwise show an alert dialog
if (!UIApplication.SharedApplication.OpenUrl (url)) {
var av = new UIAlertView ("Not supported",
"Scheme 'tel:' is not supported on this device",
null,
"OK",

null);
av.Show ();
}
};
20. Lets save our work, and then build the application by choosing Build > Build Solution or pressing Ctrl +
Shift + B. If our application compiles, we will get a success message at the bottom of the IDE:

If there are errors, we can go through the previous steps and correct any mistakes until the application
builds successfully.
21. We now have a working application and its time to add the finishing touches! We can edit the application
name and icons in the Info.plist file. Lets open Info.plist by double-clicking on it in the Solution Explorer:

22. In the iOS Application Target section, lets change the Application Name to "Phoneword":

23. To set application icons and launch images, first download the Xamarin App Icons & Launch Screens set.
In the iPhone Icons section, click directly on the (57x57) icon placeholder and select the matching icon from
the Xamarin App Icons & Launch Images directory:

Lets continue filling in all six icons. Visual Studio will replace the placeholders with our icons:

24. Next lets set the launch images. Well assign Default.png to the standard resolution (620x482)
placeholder, Default@2x.png to the Retina (3.5-inch) placeholder, and finally Default-568h@2x.png to the
Retina (4-inch) placeholder:

The image names follow iOS naming conventions for images of different densities.
25. Finally, lets test our application in the iOS Simulator. In the IDE toolbar, choose Debug and iPhone Retina
(4-inch) iOS 7.x from the drop down menus, and press Start (the green triangle that resembles a Play
button):

26. This will launch our application inside the iOS Simulator:

Phone calls are not supported in the iOS Simulator; instead, well see our alert dialog when we try to place
a call:

Congratulations on completing your first Xamarin.iOS application! Now its time to dissect the tools and skills we
just learned in the Hello, iOS Deep Dive.

You might also like