VISUAL STUDIO   Windows Mac

Hello, iOS

Introduction to iOS Development with Xamarin

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-03

This two-part guide, describes how to build a basic Xamarin.iOS application using Visual Studio for Mac or Visual Studio and develop an understanding of the fundamentals of iOS application development with Xamarin. It will introduce the tools, concepts, and steps required to build and deploy a Xamarin.iOS application.

Hello.iOS Quickstart

This guide describes how to 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:

Requirements

iOS development with Xamarin requires:

  • A Mac running OS X El Capitan (10.11) 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 Visual Studio for Mac on a Mac that fits the above specifications.
  • Latest version of Visual Studio 2015 or 2017 Professional or higher on Windows 7 or above, paired with a Mac build host that fits the above specifications.

The Xamarin.iOS OS X Installation guide is available for step-by-step installation instructions

The Xamarin.iOS Windows Installation guide is available for step-by-step installation instructions.

Before getting started, download the Xamarin App Icons set.

Visual Studio for Mac Walkthrough

This walkthrough describes how to create an application called Phoneword that translates an alphanumeric phone number into a numeric phone number.

  1. Launch Visual Studio for Mac from the Applications folder or Spotlight to bring up the Launch screen:

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

  2. From the New Solution dialog, choose the iOS > App > Single View Application template, ensuring that C# is selected. Click Next:

  3. Configure the app. Give it the Name Phoneword_iOS, and leave Identifiers, Devices, and Target as default. Click Next:

  4. Leave the Project and Solution Name as is. Choose the location of the project here, or keep it as the default:

  5. Click Create to make the Solution.

  6. Open the Main.storyboard file by double-clicking on it in the Solution Pad. This provides a way to visually to create a UI:

    Note that size classes are enabled by default. Refer to the Unified Storyboards guide to learn more about them.

  7. In the Designer Toolbar, click on View As and change it from Generic to iPhone 6:

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

  9. Grab the handles of the Dragging Controls (the circles around the control) and make the label wider:

  10. With the Label selected on the design surface, use the Properties Pad to change the Text 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.

  11. 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:

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

  13. 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:

  14. 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":

  15. 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:

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

    Save the changes by navigating to File > Save or by pressing ⌘ + s.

  17. Some logic needs to be added to the app to translate phone numbers from alphanumeric to numeric. Add a new file to the Project by right clicking on the Phoneword_iOS Project in the Solution Pad and choosing Add > New File... or pressing ⌘ + n:

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

  19. 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 Phoneword_iOS
    {
        public static class PhoneTranslator
        {
            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.

  20. Add code to wire up the user interface. To do this double-click on ViewController.cs in the Solution Pad to open it:

  21. Begin by wiring up the TranslateButton. In the ViewController class, find the ViewDidLoad method and add the following code beneath the base.ViewDidLoad() call:

    string translatedNumber = "";
    
    TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
        // Convert the phone number with text to a number
        // using PhoneTranslator.cs
        translatedNumber = PhoneTranslator.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;
        }
    };

    Include using Phoneword_iOS; if the file's namespace is different.

  22. Add code to respond to the user pressing the second button, which is named CallButton. Place the following code below the code for the TranslateButton and add using Foundation; to the top of the file:

    CallButton.TouchUpInside += (object sender, EventArgs e) => {
        // Use URL handler with tel: prefix to invoke Apple's Phone app...
        var url = new NSUrl ("tel:" + translatedNumber);
    
        // ...otherwise show an alert dialog
        if (!UIApplication.SharedApplication.OpenUrl (url)) {
            var alert = UIAlertController.Create ("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
            alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null));
            PresentViewController (alert, true, null);
        }
    };
  23. Save the changes and then build the application by choosing Build > Build All or pressing ⌘ + B. If the application compiles, a success message will appear at the top of the IDE:

    If there are errors, go through the previous steps and correct any mistakes until the application builds successfully.

  24. The basic application functionality is now working and it’s time to add the finishing touches! Edit the application name and icons in the Info.plist file. To do this open Info.plist by double-clicking on it in the Solution Pad:

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

  26. To set application icons, first download the Xamarin App Icons set. Double click on Assets.xcassets in the Solution Pad and select AppIcon on the left of the opened document. In the Icons section, click directly on the (57x57) icon placeholder and select the matching icon from the Xamarin App Icons directory:

    Continue filling in all icons. Visual Studio for Mac will replace the placeholders with the icons:

    The image names follow iOS naming conventions for images of different densities.

  27. Finally, test the application in the iOS Simulator. In the top left of the IDE, choose Debug from the first dropdown, and iPhone 6 iOS x.x from the second dropdown, and press Start (the triangular button that resembles a Play button):

    ℹ️

    Note: At present, due to a requirement from Apple, it may be necessary to have a a development certificate or signing identity in order to build you code for device or simulator. Follow the steps in the Device Provisioning guide to set this up.

  28. This will launch the application inside the iOS Simulator:

    Phone calls are not supported in the iOS Simulator; instead, you will see an alert dialog when trying to place a call:

Visual Studio Walkthrough

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

Note: This walkthrough uses Visual Studio Enterprise 2017 on a Windows 10 Virtual Machine. Your set up can differ from this, as long as it meets the requirements above, but be aware that some screenshots may look different to your set up.

ℹ️

Before proceeding with this walkthrough you must have already connected to your Mac from Visual Studio. This is because Xamarin.iOS relies on Apple's tooling to build and launch the iOS Designer and applications. To get set up, follow the steps in the Connecting to Mac guide.

  1. Launch Visual Studio from the Start menu:

    In the search box under New Solution enter Single View App, and select Single View App (iPhone) to create a new Xamarin.iOS solution:

  2. Name the Project and Solution Phoneword, as illustrated below:

  3. Press OK to create the new Project

  4. Confirm that the Xamarin Mac Agent icon in the toolbar is green.

    Confirm that the Xamarin Mac Agent icon in the toolbar is green

    If it isn't connected, follow the steps in the configuration guide.

  5. Open the Main.storyboard file in the iOS Designer by double-clicking on it in the Solution Explorer:

  6. In the Designer Toolbar, click on View As and change it from Generic to iPhone 6:

  7. Open the Toolbox tab, type “label” into the search bar and drag a Label onto the design surface (the area in the center):

  8. Next, grab the handles of the Dragging Controls (the circles around the control – make sure they are circles they don't look like 'bones') and make the label wider:

  9. With the Label selected on the design surface, use the Properties Windows to change the Text 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.

  10. 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:

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

  12. 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:

  13. 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":

  14. Repeat the previous two steps 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:

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

    Save the changes by navigating to File > Save All or by pressing Ctrl + s.

  16. Code to translate phone numbers from alphanumeric to numeric. To do this, first add a new file to the Project by right-clicking on the Phoneword Project in the Solution Explorer and choosing Add > New Item... or pressing Ctrl + Shift + A:

  17. In the New File dialog, select Apple > Class and name the new file PhoneTranslator:

    ⚠️

    Make sure that you select the 'class' template that has a C# in the icon. Otherwise you may not be able to reference this new class.

  18. This creates a new C# class. Remove all the template code and replace it with the following code:

    using System.Text;
    using System;
    
    namespace Phoneword
    {
        public static class PhoneTranslator
        {
            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.

  19. Double-click on ViewController.cs in the Solution Explorer to open it, so that logic can be added to handles interactions with the buttons:

  20. Begin by wiring up the TranslateButton. In the ViewController class, find the ViewDidLoad method. Add the following button code inside ViewDidLoad, beneath the base.ViewDidLoad() call:

    string translatedNumber = "";
    
    TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
    
      // Convert the phone number with text to a number
      // using PhoneTranslator.cs
      translatedNumber = PhoneTranslator.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;
        }
    };

    Include using Phoneword_iOS; if the file's namespace is different.

  21. Add code to respond to the user pressing the second button, which is named CallButton. Place the following code below the code for the TranslateButton and add using Foundation; to the top of the file:

    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 alert = UIAlertController.Create ("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
                        alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null));
                        PresentViewController (alert, true, null);
                    }
    };
  22. Save the changes, and then build the application by choosing Build > Build Solution or pressing Ctrl + Shift + B. If the application compiles, a success message will appear at the bottom of the IDE:

    If there are errors, go through the previous steps and correct any mistakes until the application builds successfully.

  23. The basic application functionality is now working and it’s time to add the finishing touches. Edit the application name and icons in the Project Properties To do this right-click on the Project in the Solution Explorer and select properties. Go to the iOS Application Tab.:

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

  25. To set application icon, an Asset Catalog that will hold all the images is required. To create this, right-click on Asset Catalogs in the Solution Explorer and select Add Asset Catalog:

    Name the Asset Catalog Media and press Add:

  26. To set application icons and launch images, first download the Xamarin App Icons set. To start adding the icons, click directly on the (58x58) icon placeholder and browse to your folder location. Select the matching icon from the Xamarin App Icons directory:

    Continue filling in all the icons. Visual Studio will replace the placeholders with the app icons:

  27. Go to the application's Project options to tell the application to use the Asset Catalog for app icons. To do this right-click on the Project name and browse to Properties. Locate the iOS Application section. Under App, Spotlight and Settings, set the Asset Catalogs dropdown to Media > App Icons:

  28. Finally, test the application in the iOS Simulator. In the IDE toolbar, choose Debug and iPhone 6 iOS x.x from the drop down menus, and press Start (the green triangle that resembles a Play button):

    ℹ️

    Note: At present, due to a requirement from Apple, it may be necessary to have a a development certificate or signing identity in order to build you code for device or simulator. Follow the steps in the Device Provisioning guide to set this up.

  29. This will launch the application inside the iOS Simulator:

    Phone calls are not supported in the iOS Simulator; instead, an alert dialog will display when trying to place a call:

Congratulations on completing your first Xamarin.iOS application!

Now it’s time to dissect the tools and skills shown in this guide in the Hello, iOS Deep Dive.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.