MobileAndroidCreating an iOS Solution with Xamarin

Creating an iOS Solution with Xamarin

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This is part two of a two-part article series that walks you through the complete process of using Xamarin to create a simple cross-platform app with .NET and C# that runs on both Android and iOS. In part one, I introduced Xamarin, walked you through the process of creating a cross-platform code library with Xamarin, and guided you through the creation of the Android implementation of the cross-platform app. In this article, I’ll cover the creation of the iOS implementation.

Picking Up Where We Left Off

In part one we created a portable class library that contains a class called SillyString that uses Linq internally to return the number of upper case characters a string contains. Throughout this article I’ll walk you through how to implement the iOS application with Xamarin leveraging the existing portable class library to provide the same features as the Android application.

Remember that you are sharing the source code and project between a Windows computer and an OS X computer. The best way to do this is with a source code control system such as Git but for a simple project like the one I discuss in this article, you can use a shared drive technology such as OneDrive, Google Drive, or Dropbox.

As I mentioned in part one, all of the iOS development work performed with Xamarin Studio must be performed on an OS X computer therefore all of the steps covered in the remainder of the article occur on an OS X computer.

Note: Just a reminder that if you’re using the Business or Enterprise editions of Xamarin you are able to perform your iOS development work in Visual Studio on a Windows Computer.

Creating the iOS Application Solution

To get started we’ll first create a blank Xamarin Studio solution on the OS X computer. To create the solution, do the following.

  • On the OS X computer, open Xamarin Studio
  • Open the New Solution dialog by selecting File from the Xamarin Studio menu, then selecting New followed by Solution…
  • In the New Solution dialog, choose Other in the left pane and Blank Solution in the right pane
  • Enter the solution name as MyXPlatformiOS

The New Solution dialog should now appear similar to this figure.

BlankSolution_NewSolution_iOS
BlankSolution_NewSolution_iOS

  • Click OK to create the solution.

Adding the Shared Library Project

Before you create the project for the iOS application, add the shared library project you created in part one to the new solution. This project allows you to have a single project providing the business logic for both the Android and iOS apps. To add the shared library project to the solution do the following.

  • Verify that you have successfully copied the complete shared library project folder from the Windows computer to the OS X computer using either a source code control system or shared drive technology.
  • In Xamarin Studio, open the solution context-menu by right-clicking (or two-finger clicking) on the solution name, MyXPlatformiOS, in the Solution view.
  • Open the New Project dialog by selecting Add from the context menu followed by Add Existing Project…
  • Navigate to and select the MyXPlatformLib.csproj project file.
  • Click Open to add the project to the solution.

Creating the iOS Application Project

To create the actual iOS application, you need to create an iOS application project. To create the project, do the following.

  • Open the solution context menu by right-clicking (or two-finger clicking) on the solution name, MyXPlatformiOS, in the Solution view.
  • Open the New Project dialog by selecting Add from the context menu followed by Add New Project…
  • Expand the iOS node in the left pane of the New Project dialog and then select iPhone.
  • In the right pane of the New Project dialog select Single View Application.
  • Enter the project name as MyXPlatformiOS (same name as the solution).

The New Project dialog should now appear similar to this figure.

MyXPlatformiOS_NewProject
MyXPlatformiOS_NewProject

  • Click OK to create the project.

The newly generated project contains a single screen iOS application. The complete Xamarin Studio Solution view should look similar to the following figure.

XS_CompleteSolution
XS_CompleteSolution

We’ll now walk through how to add UI controls to the screen and tie in the logic from our shared library.

Adding Controls to the UI

To add controls to the UI of the iOS application you must leave Xamarin Studio and perform the actual UI design work using XCode, which is the standard iOS Objective-C development environment. Don’t worry though; Xamarin Studio fully cooperates with XCode. Xamarin Studio automatically starts XCode when you need it, and Xamarin Studio automatically reads the results of the work performed in XCode and imports the appropriate code into the Xamarin project.

To open XCode and layout the UI controls, double click on the file named MyXPlatformiOSViewController.xib in the Solution view. Once XCode opens, it should appear similar to the following figure.

XCode_InitialOpen
XCode_InitialOpen

To layout the user interface, perform the following steps.

  • Locate the Object Library window, which is in the lower right corner of XCode, as shown in the following figure.

    XCode_ObjectLibrary
    XCode_ObjectLibrary

  • Find Text Field in the Object Library and drag it onto the design surface; you may have to scroll the Object Library to locate Text Field.
  • Position the Text Field near the top of the design surface and size it so it nearly fills the horizontal space.
  • Locate the field near the right edge of XCode labeled Placeholder and enter the value Input Field.
  • Drag Button from the Object Library onto the design surface.
  • Position the Button just below the Text Field and size it to nearly fill the horizontal space.
  • Drag Label from the Object Library onto the design surface.
  • Position the Label just below the Button and size it to nearly fill the horizontal space.
  • Locate the Label text near the right edge of XCode and change the Label text to Output Field.

The design surface should now look similar to the following figure.

XCode_DesignLayout
XCode_DesignLayout

Making the Controls Accessible in Code

With the design layout in place, you need to perform some additional steps to make the controls accessible in code. You must add what’s referred to as an Outlet for each of the controls. Before you can add the control Outlets you must first open the XCode Assistant editor to the MyXPlatformiOSViewController.h file by doing the following.

  • Click the Assistant editor button located near the top right edge of XCode as shown in the following figure.

XCode_AssistantEditor
XCode_AssistantEditor

  • By default the Assistant editor opens to the MyXPlatformiOSViewController.m file; change to the MyXPlatformiOSViewController.h file by selecting MyXPlatformiOSViewController.h from the dropdown window located at the top of the Assistant editor as shown in the following image.

XCode__SelectHFile
XCode__SelectHFile

The control Outlets are simply identifiers for each of the controls that Xamarin will use to generate C# properties for each control. To add the control Outlets, do the following.

    • Hold the keyboard Control-Key down and drag the Input Field Text Field over to the Assistant editor until you see a box appear that says Outlet, Action, or Outlet Collection; when this appears release the field.
    • In the window that opens, enter InputField as the Name as shown in the following figure.

XCode_CreateOutlet
XCode_CreateOutlet

  • Click Connect to complete the Outlet creation.
  • Repeat these steps to create an Outlet for the Button control named Button.
  • Repeat these steps to create an Outlet for the Output Field named OutputField.

After you create all of the Outlets, the MyXPlatformiOSViewController.h will look similar to the following image.

XCode_OutletComplete
XCode_OutletComplete

To complete the process of tying the Controls into your code you must exit XCode by selecting Quit XCode from the XCode menu. When you exit XCode and return to Xamarin Studio, Xamarin Studio will automatically create C# properties corresponding to each of the Outlets you created in XCode. The generated properties are named the same as the Outlets.

Making the Shared Library Available to the iOS App Project

To use the shared library in the Android app project you must first add a reference to the shared library. To add the reference, do the following.

  • Open the context menu by right clicking (or two-finger clicking) on References under the MyXPlatformiOS project in the Solution view.
  • Open the Edit References dialog by selecting Edit References from the context menu.
  • In the Edit References dialog select the Projects tab.
  • Select the checkbox next to MyXPlatformLib.
  • Click OK.

Using the Shared Library in the iOS App

In this app all of the code related to the UI will be in the main application screen’s source file, MyXPlatformiOSViewController.cs. Locate MyXPlatformiOSViewController.cs in the Solution view and double click on it to open the file in the editor.

The first thing to do is add a using statement for MyXPlatformLib to the MainActivity.cs source file to make the types available without the need to namespace qualify them.

using MyXPlatformLib;

Bringing the Shared Library and iOS App Together

Within the MyXPlatformiOSViewController class locate the ViewDidLoad method. This method is called after the application fully creates the screen and is where we can add the code to handle when the user selects the button.

Within the ViewDidLoad method after the call to the base.ViewDidLoad() add the code to associate a delegate with the Button controls TouchUpInside event as shown here;

public override void ViewDidLoad ()
{
  base.ViewDidLoad ();
                     
  Button.TouchUpInside += delegate {
 
  };
}

The TouchUpInside event is fired when the user touches the button on screen. Notice that unlike Android where you explicitly request a reference to the UI controls with calls to the FindViewById method, Xamarin automatically adds properties for the controls. The control properties are created using the Outlets you added earlier.

Within the TouchUpInside event delegate create an instance of the SillyString class passing the InputField control’s Text property to the SillyString constructor and assign the SillyString class’ UpperCount property to a local variable.

SillyString sillyString = new SillyString(InputField.Text);
int upperCount = sillyString.UpperCount;

The last step is to display the number of upper case characters by assigning the appropriate message to the OutputField control’s Text property.

OutputField.Text = String.Format("{0} upper case chars", upperCount);

The complete ViewDidLoad method now appears as shown in the following code listing.

public override void ViewDidLoad ()
{
  base.ViewDidLoad ();
       
  Button.TouchUpInside += delegate {
    SillyString sillyString = new SillyString(InputField.Text);
    int upperCount = sillyString.UpperCount;
    OutputField.Text = String.Format("{0} upper case chars", upperCount);
  };
}

Testing the iOS App

The easiest way to test your app is to use the iOS simulator, which was installed as part of the XCode installation you performed earlier.  Xamarin Studio automatically starts the simulator when you run the application so you do not need to perform an explicit launch of the simulator.

Before you can test the app, set the MyXPlatformiOS project as the startup project by doing the following.

  • In Xamarin Studio, open the project context menu by right clicking (or two-finger clicking) on the MyXPlatformiOS project in the Solution view (be sure to click on the project name and not the solution name).
  • Select Set As Startup Project.

Running the App

Now you can launch the app to run on the iOS Simulator by simply selecting Run from the Xamarin Studio menu and then selecting Start Without Debugging. The process of starting the simulator may take a few minutes the first time you use it.

Once the simulator starts, you should now see your application running in the simulator as shown in the following figure.

 

Simulator_FirstStart
Simulator_FirstStart

Verifying App Behavior

Once the app is started, perform the following steps to verify that the app behaves as expected.

  • Click in the Input Field, which will cause the simulator to display the soft keyboard.
  • Using the soft keyboard, enter a word or phrase of your choice such as Hello World.
  • Click the Button.

The app will then display the number of upper case characters contained in the word or phrase you entered as shown in the following figure.

Simulator_AppTest
Simulator_AppTest

Congratulations! You now have a complete cross-platform system in place. Your iOS app is working. It provides the same user experience as the Android app and leverages the same shared business logic.

Conclusion

Xamarin is a powerful cross-platform development environment that allows you to leverage a consistent development experience and the full power of .NET and C# to create Android and iOS apps. With Xamarin, your applications can fully embrace the features and behaviors of each platform while creating a common core of logic and behavior independent of the target platform.

As you’ve seen throughout the two parts of this article, you are able to create class libraries that provide complete business logic functionality across the two platforms. At the same time, you are able to expose the rich, unique features of each platform assuring that your iOS app feels like iOS and your Android app feels like Android.

About the Author

Jim Wilson is president of JW Hedgehog, Inc., a consulting firm specializing in solutions for the Android, iOS, and Microsoft platforms. He is Lead Mobile Developer for Spectafy, a start up empowering us all to make informed decisions through a combination of community and access to live, location-specific, crowd-sourced photos. Jim is also a regular contributor of mobility-related training materials to Pluralsight, a leading provider of online developer training. Jim’s latest book is “Creating Dynamic UI with Android Fragments”. Jim and his wife, along with several cats, live in Celebration, Florida (just 3 miles from Walt Disney World). Checkout Jim’s blog where he talks about a variety of mobile software development issues as well as the fun of life just 3 miles from the “House of Mouse”.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories