Reader small image

You're reading from  Xamarin 4.x Cross-Platform Application Development - Third Edition

Product typeBook
Published inDec 2016
Reading LevelIntermediate
Publisher
ISBN-139781786465412
Edition3rd Edition
Languages
Tools
Right arrow
Author (1)
Jonathan Peppers
Jonathan Peppers
author image
Jonathan Peppers

Jonathan Peppers is a Xamarin MVP and lead developer on popular apps and games at Hitcents such as the Hanx Writer (for Tom Hanks) and the Draw a Stickman franchise. Jon has been working with C# for over 10 years working on a wide range of projects at Hitcents. Jon began his career working Self-Checkout software written in WinForms and later migrated to WPF. Over his career, he has worked with many .NET-centric technologies such as ASP.Net WebForms, MVC, Windows Azure, WinRT/UWP, F#, and Unity3D. In recent years, Hitcents has been heavily investing in mobile development with Xamarin, and has development over 50 mobile applications across multiple platforms.
Read more about Jonathan Peppers

Right arrow

Chapter 3. Code Sharing Between iOS and Android

Xamarin's tools promise to share a good portion of your code between iOS and Android while taking advantage of the native APIs on each platform where possible. Doing so is an exercise in software engineering more than a programming skill or having the knowledge of each platform. To architect a Xamarin application for enabling code sharing, it is a must to separate your application into distinct layers. We'll cover the basics as well as specific options to consider certain situations.

In this chapter, we will cover:

  • The MVVM design pattern for code sharing

  • Project and solution organization strategies

  • Portable Class Libraries (PCLs)

  • Preprocessor statements for platform-specific code

  • Dependency Injection (DI) simplified

  • Inversion of Control (IoC)

Learning the MVVM design pattern


The Model-View-ViewModel (MVVM) design pattern was originally invented for WPF (Windows Presentation Foundation) applications using XAML for separating the UI from business logic and taking full advantage of data binding. Applications architected in this way have a distinct ViewModel layer that has no dependencies on its user interface. This architecture in itself is optimized for unit testing as well as cross-platform development. Since an application's ViewModel classes have no dependencies on the UI layer, you can easily swap an iOS user interface for an Android one and write tests against the ViewModel layer. The MVVM design pattern is also very similar to the MVC design pattern discussed in the previous chapters.

The MVVM design pattern includes the following:

  • Model: The model layer is the backend business logic driving the application and any business objects to go along with it. This can be anything from making web requests to a server to using a backend...

Comparing project organization strategies


You might be asking yourself at this point, how do I set up my solution in Xamarin Studio to handle shared code and also have platform-specific projects? Xamarin.iOS applications can only reference Xamarin.iOS class libraries; so, setting up a solution can be problematic. There are several strategies for setting up a cross-platform solution, each with its own advantages and disadvantages.

Options for cross-platform solutions are as follows:

  • File Linking: For this option, you would start with either a plain .NET 4.0 or .NET 4.5 class library containing all the shared code. You would then have a new project for each platform you want your app to run on. Each platform-specific project would have a subdirectory with all of the files linked in from the first class library. To set this up, add the existing files to the project, and select the Add a link to the file option. Any unit tests can run against the original class library. The advantages and disadvantages...

Setting up a shared project


To understand each option completely and what situations call for, let's define a solution structure for both shared projects and portable class libraries. Let's use the product search example from earlier in the chapter and set up a solution for each approach.

To set up a shared project, perform the following steps:

  1. Open Xamarin Studio and start a new solution.

  2. Select a new Single View App under the Multiplatform | App section.

  3. Name the app ProductSearch, and select Use Shared Library.

  4. Complete this new project wizard and Xamarin Studio will generate three projects: ProductSearch, ProductSearch.Droid, and ProductSearch.iOS.

  5. Add the Product, ProductRepository, and ProductViewModel classes to the ProductSearch project from earlier in this chapter. You will need to add using System.Threading.Tasks; and using System.Linq; where needed.

  6. Click on Build | Build All from the menu at the top to double-check everything, and you have successfully set up a cross-platform solution...

Working with portable class libraries


A portable class library (PCL) is a C# library project that is able to be supported on multiple platforms including iOS, Android, Windows, Windows Store apps, Windows phone, Silverlight, and Xbox 360. PCLs have been an effort by Microsoft to simplify development across different versions of the .NET framework. Xamarin has also added support on iOS and Android for PCLs. Many popular cross-platform frameworks and open source libraries are starting to develop PCL versions such as Json.NET and MVVMCross.

To set up a shared project, perform the following steps:

  1. Open Xamarin Studio and start a new solution.

  2. Select a new Single View App under the Multiplatform | App section. Or in Visual Studio, Cross-platform | Blank App (Native Portable).

  3. Name the app ProductSearch, and select Use Portable Library.

  4. Complete this new project wizard and Xamarin Studio will generate three projects: ProductSearch, ProductSearch.Droid, and ProductSearch.iOS.

  5. Add the Product, ProductRepository...

Using preprocessor statements


When using shared projects, one of your most powerful tools is the use of preprocessor statements. If you are unfamiliar with them, C# has the ability to define preprocessor variables such as #define IPHONE, and then using #if IPHONE or #if !IPHONE.

The following is a simple example of using the technique:

#if IPHONE 
  Console.WriteLine("I am running on iOS"); 
#elif ANDROID 
  Console.WriteLine("I am running on Android"); 
#else 
  Console.WriteLine("I am running on ???"); 
#endif 

In Xamarin Studio, you can define preprocessor variables in your project's options under Build | Compiler | Define Symbols, delimited with semicolons. These will be applied to the entire project. Be warned that you must set up these variables for each configuration setting in your solution (Debug and Release); it can be an easy step to miss. You can also define these variables at the top of any C# file by declaring #define IPHONE, but they will only...

Simplifying dependency injection


Dependency injection at first seems like a complex topic, but for the most part it is a simple concept. It is a design pattern aimed at making your code within your applications more flexible so that you can swap out certain functionality when needed. The idea builds around setting up dependencies between classes in an application so that each class only interacts with an interface or base/abstract class. This gives you the freedom to override different methods on each platform when you need to fill in native functionality.

The concept originated from the SOLID object-oriented design principles, which is a set of rules you might want to research if you are interested in software architecture. The D in SOLID stands for dependencies. Specifically, the principle declares that a program should depend upon abstractions, not concretions (concrete types).

To build upon this concept, let's walk through the following example:

  1. Let's assume we need to store a setting in...

Implementing Inversion of Control


You might be asking yourself at this point of time, how do I switch out different classes such as the ISettings example? Inversion of Control (IoC) is a design pattern meant to complement the dependency injection and solve this problem. The basic principle is that many of the objects created throughout your application are managed and created by a single class. Instead of using the standard C# constructors for your ViewModel or Model classes, a service locator or factory class would manage them throughout the application.

There are many different implementations and styles of IoC, so let's implement a simple service locator class to use throughout the remainder of this book as follows:

public static class ServiceContainer 
{ 
  static readonly Dictionary<Type, Lazy<object>> services = 
    new Dictionary<Type, Lazy<object>>(); 
 
  public static void Register<T>(Func<T> function) 
  { 
...

Summary


In this chapter, we learned about the MVVM design pattern and how it can be used to better architect cross-platform applications. We compared several project organization strategies for managing a Xamarin Studio solution containing both iOS and Android projects. We went over portable class libraries as the preferred option for sharing code and how to use preprocessor statements as a quick and dirty way to implement platform-specific code.

After completing this chapter, you should be up to speed with several techniques for sharing code between iOS and Android applications using Xamarin Studio. Using the MVVM design pattern will help you separate your shared code and code that is platform specific. We also covered several options for setting up cross-platform Xamarin solutions. You should also have a firm understanding of using the dependency injection and Inversion of Control to give your shared code access to the native APIs on each platform. In our next chapter, we will begin with...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Xamarin 4.x Cross-Platform Application Development - Third Edition
Published in: Dec 2016Publisher: ISBN-13: 9781786465412
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jonathan Peppers

Jonathan Peppers is a Xamarin MVP and lead developer on popular apps and games at Hitcents such as the Hanx Writer (for Tom Hanks) and the Draw a Stickman franchise. Jon has been working with C# for over 10 years working on a wide range of projects at Hitcents. Jon began his career working Self-Checkout software written in WinForms and later migrated to WPF. Over his career, he has worked with many .NET-centric technologies such as ASP.Net WebForms, MVC, Windows Azure, WinRT/UWP, F#, and Unity3D. In recent years, Hitcents has been heavily investing in mobile development with Xamarin, and has development over 50 mobile applications across multiple platforms.
Read more about Jonathan Peppers