Book Image

iOS Development with Xamarin Cookbook

By : Dimitrios Tavlikos (USD)
Book Image

iOS Development with Xamarin Cookbook

By: Dimitrios Tavlikos (USD)

Overview of this book

Table of Contents (22 chapters)
iOS Development with Xamarin Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating an iOS project with Xamarin Studio


In this recipe, we will discuss how to create our first iOS project with Xamarin Studio.

Getting ready...

Now that we have all the prerequisites installed, we will discuss how to create our first iOS project with Xamarin Studio.

Start Xamarin Studio. It can be found in the Applications folder. Xamarin Studio's default project location is /Users/{yourusername}/Projects. If it does not exist on the hard disk, it will be created when we create out first project. If you want to change the folder, go to Xamarin Studio | Preferences from the menu bar. Select Load/Save in the pane on the left, enter the preferred location for the projects in the Default Solution location field, and click on OK.

How to do it...

The first thing that is loaded when starting Xamarin Studio is its start page. Perform the following steps to create an iOS project with Xamarin Studio:

  1. Navigate to File | New | Solution... from the menu bar. A window that provides us with the available project options will appear.

  2. In the pane on the left of this window, go to C# | iOS | iPhone. The iPhone project templates will be presented on the middle pane.

  3. Select Single View Application.

  4. Finally, enter MyFirstiOSProject for Solution name and click on OK. The following screenshot displays the New Solution window:

That was it. You just created your first iPhone project. You can build and run it; iOS Simulator will start, with a blank light-gray screen nevertheless.

Note

The project templates may be different from the ones shown in the preceding screenshot.

How it works...

Let's see what goes on behind the scenes.

When Xamarin Studio creates a new iOS project, it creates a series of files. The solution files can be viewed in the Solution pad on the left side of Xamarin Studio window. If the Solution pad is not visible, it can be activated by checking on View | Pads | Solution from the menu bar.

The files shown in the following screenshot are the essential files that form an iPhone project:

MyFirstiOSProjectViewController.xib

MyFirstiOSProjectViewController.xib is the file that contains the view of the application. XIB files are basically XML files with a specific structure that Xcode can read. The files contain information about the user interface, such as the type of controls it contains, their properties, and Outlets.

Note

If MyFirstiPhoneProjectViewController.xib, or any other file with the .xib suffix, is double-clicked, Xamarin Studio automatically opens the file in Xcode's Interface Builder.

When we create a new interface with Interface Builder and save it, it is saved in the XIB format.

MyFirstiOSProjectViewController.cs

MyFirstiOSProjectViewController.cs is the file that implements the view's functionality. These are the contents of the file when it is created:

using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace MyFirstiOSProject
{
    public class MyFirstiOSProjectViewController : UIViewController
    {
        public MyFirstiOSProjectViewController () : base ("MyFirstiOSProjectViewController", null)
        {
        }

        public override void DidReceiveMemoryWarning ()
        {
            // Releases the view if it doesn't have a superview.base.DidReceiveMemoryWarning ();
            
            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            
            // Perform any additional setup after loading the view, typically from a nib.
        }
}
}

Note

Xamarin.iOS was formerly known as MonoTouch. For proper code compatibility, the namespaces have not been renamed.

The code in this file contains the class which corresponds to the view that will be loaded, along with some default method that overrides. These methods are the ones that we will use more frequently when we create view controllers. A brief description of each method is listed as follows:

  • ViewDidLoad: This method is called when the view of the controller is loaded. This is the method we use to initialize any additional component.

  • DidReceiveMemoryWarning: This method is called when the app receives a memory warning. This method is responsible for releasing resources that are not needed at the time.

MyFirstiOSProjectViewController.designer.cs

MyFirstiOSProjectViewController.designer.cs is the file that holds our main window's class information in C# code. Xamarin Studio creates one .designer.cs file for every XIB that is added in a project. The file is autogenerated every time we save a change in our XIB through Interface Builder. This is taken care of by Xamarin Studio so that the changes we make in our interface are reflected right away in our code. We must not make changes to this file directly, since when the corresponding XIB is saved with Interface Builder, they will be lost. Also, if nothing is saved through Interface Builder and if changes are made to it manually, it will most likely result in a compilation error.

These are the contents of the file when a new project is created:

//
// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using MonoTouch.Foundation;

namespace MyFirstiOSProject
{
    [Register ("MyFirstiOSProjectViewController")]
    partial class MyFirstiOSProjectViewController
    {
        void ReleaseDesignerOutlets ()
        {
        }
    }
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

This file contains the other partial declaration of our MyFirstiOSProjectViewController class. It is decorated with the Register attribute.

The Register attribute is used to expose classes to the underlying Objective-C runtime. The string parameter declares by what name our class will be exposed to the runtime. It can be whatever name we want it to be, but it is a good practice to always set it to our C# class' name. The attribute is used heavily in the internals of Xamarin.iOS, since it is what binds all the native NSObject classes with their C# counterparts.

Note

NSObject is a root class or base class. It is the equivalent of System.Object in the .NET world. The only difference between the two is that all .NET objects inherit from System.Object, but most, not all, Objective-C objects inherit from NSObject in Objective-C. The C# counterparts of all native objects that inherit from NSObject also inherit from its Xamarin.iOS NSObject counterpart.

AppDelegate.cs

The AppDelegate.cs file contains the AppDelegate class. The contents of the file are listed below:

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace MyFirstiOSProject
{
    // The UIApplicationDelegate for the application. This classis responsible for launching the
    // User Interface of the application, as well as listening(and optionally responding) to
    // application events from iOS.
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;
        MyFirstiOSProjectViewController viewController;
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching (UIApplication app,NSDictionary options)
        {
            window = new UIWindow (UIScreen.MainScreen.Bounds);
            
            viewController = new MyFirstiOSProjectViewController ();
            window.RootViewController = viewController;
            window.MakeKeyAndVisible ();
            
            return true;
        }
    }
}

The first part is familiar to .NET developers and consists of the appropriate using directives that import the required namespaces to use. Consider the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

The first three using directives allow us to use the specific and familiar namespaces from the .NET world with Xamarin.iOS.

Note

System, System.Collections.Generic, System.Linq: Although the functionality that the three namespaces provide is almost identical to their well-known .NET counterparts, they are included in assemblies specifically created for use with Xamarin.iOS and shipped with it, of course. An assembly compiled with .NET cannot be directly used in a Xamarin.iOS project.

The MonoTouch.Foundation namespace is a wrapper around the native Objective-C Foundation Framework, which contains classes that provide basic functionality. These objects' names share the same NS prefix that is found in the native Foundation Framework. Some examples are NSObject, NSString, NSValue, and so on. Apart from the NS-prefixed objects, the MonoTouch.Foundation namespace contains all of the attributes that are used for binding to native objects, such as the Outlet and Register attributes we saw earlier. The MonoTouch.UIKit namespace is a wrapper around the native Objective-C UIKit Framework. As its name suggests, the namespace contains classes, delegates, and events that provide us with interface functionality. Almost all the objects' names share the same UI prefix. It should be clear at this point that these two namespaces are essential for all Xamarin.iOS apps, and their objects will be used quite frequently.

The class inherits from the UIApplicationDelegate class, qualifying it as our app's delegate object.

Note

The concept of a delegate object in the Objective-C world is somewhat different from delegate in C#. It will be explained in detail in Chapter 2, User Interface – Views.

The AppDelegate class contains two fields and one method:

UIWindow window;MyFirstiOSProjectViewController viewController; 
//..
public override bool FinishedLaunching (UIApplication app, NSDictionary options) {

The UIWindow object defines the main window of our application, while the MyFirstiOSProjectViewController object is the variable that will hold the app's view controller.

Note

An iOS app typically has only one window of type UIWindow. UIWindow is the first control that is displayed when an app starts, and every subsequent view is hierarchically added below it.

The FinishedLaunching method, as its name suggests, is called when the app has completed its initialization process. This is the method where we must present the user interface to the user. The implementation of this method must be lightweight; if it does not return in time from the moment it is called, iOS will terminate the app. This provides faster user interface loading time to the user by preventing developers from performing complex and long-running tasks upon initialization, such as connecting to a web service to receive data. The app parameter is the application's UIApplication object, which is also accessible through the static property UIApplication.SharedApplication. The options parameter may or may not contain information about the way the app was launched. We do not need it for now.

The default implementation of the FinishedLaunching method for this type of project is as follows:

  • The UIWindow object is initialized with the size of the screen as follows:

    window = new UIWindow (UIScreen.MainScreen.Bounds);
  • The view controller is initialized and set as the window's root view controller as follows:

    viewController = new MyFirstiPhoneProjectViewController();
    window.RootViewController = viewController;
    window.MakeKeyAndVisible ();
    return true;

The window is displayed on the screen with the window.MakeKeyAndVisible() call and the method returns. This method must be called inside the FinishedLaunching method, otherwise the app's user interface will not be presented as it should be to the user. Last but not least, the return true line returns the method by marking its execution completion.

Main.cs

Inside the Main.cs file is where the runtime life cycle of the program starts as shown in the following code:

namespace MyFirstiOSProject
{
    public class Application
    {
        // This is the main entry point of the application.
        static void Main (string[] args)
        {
            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main (args, null, "AppDelegate");
        }
    }
}

It is much like the following call in a .NET System.Windows.Forms application:

Application.Run(new Form1());

The UIApplication.Main method starts the message loop or run loop that is responsible for dispatching notifications to the app through the AppDelegate class with event handlers that we can override. Event handlers such as FinishedLaunching, ReceiveMemoryWarning, or DidEnterBackground are only some of these notifications. Apart from the notification dispatching mechanism, the UIApplication object holds a list of all UIWindow objects that exist, typically one. An iOS app must have one UIApplication object, or a class that inherits from it, and this object must have a corresponding UIApplicationDelegate object. This is the AppDelegate class implementation we saw earlier.

Info.plist

The Info.plist file is basically the app's settings file. It has a simple structure of properties with values that define various settings for an iOS app, such as the orientations it supports, its icons, supported iOS versions, what devices it can be installed on, and so on. If we double-click on this file in Xamarin Studio, it will open in the embedded editor specifically designed for this file. Our file in a new project looks like the following screenshot:

We can also access Info.plist through the project's options window under iOS Application.

There's more...

Xamarin Studio provides many different project templates for developing iOS apps. Here is a list that describes what each project template is for:

  • Empty project: This is an empty project without any views.

  • Utility application: This is a special type of iOS app that provides one screen for functionality and, in many cases, another one for configuration.

  • Master-detail application: This type of project creates a template that supports navigating through multiple screens. It contains two view controllers.

  • Single view application: This template type is the one we used in this recipe.

  • Tabbed application: This is a template that adds a tab bar controller, which manages two view controllers in a tab-like interface.

  • OpenGL application: This is a template for creating OpenGL-powered applications or games.

These templates are available for the iPhone, iPad, and Universal (both iPhone and iPad) projects. They are also available in Interface Builder's storyboarding app design.

Note

Unless stated, all project templates referring to the iPhone are suitable for the iPod Touch as well.

List of Xamarin.iOS assemblies

Xamarin.iOS-supported assemblies can be found at http://ios.xamarin.com/Documentation/Assemblies.

See also

  • The Creating the UI and Accessing the UI with Outlets recipes

  • The Adding and customizing views recipe in Chapter 2, User Interface – Views