left-icon

Xamarin.Forms for macOS Succinctly®
by Alessandro Del Sole

Previous
Chapter

of
A
A
A

CHAPTER 1

Getting Started with Xamarin.Forms

Getting Started with Xamarin.Forms


Before you start writing mobile apps with Xamarin.Forms, you first need to understand the state of mobile app development today, and how Xamarin fits into it. Also, you need to set up your development environment to be able to build, test, debug, and deploy your apps to Android and iOS devices. This chapter introduces Xamarin as a set of tools and services and Xamarin.Forms as the platform you will use, and then presents the tools and hardware you need for real-world development.

Introducing Xamarin and Xamarin.Forms

Xamarin is the name of a company that Microsoft acquired in 2016 and, at the same time, the name of a set of development tools and services that developers can use to build native apps for iOS and Android (and Windows 10 when developing on Windows) in C#. Xamarin’s main goal is to make it easier for .NET developers to build native apps for Android and iOS reusing their existing skills. The reason for this goal is simple: building apps for Android requires you to know Java and Android Studio or Eclipse; building apps for iOS requires you to know Objective-C or Swift and Xcode; and when working on Windows, building apps for Windows 10 requires you to know C# and Visual Studio. As an existing .NET developer, whether you are experienced or a beginner, getting to know all the possible platforms, languages, and development environments is extremely difficult, and the costs are extremely high.

Xamarin allows you to build native apps with C#, based on a cross-platform, open-source porting of the .NET Framework called Mono. From a development point of view, Xamarin offers a number of flavors:

  • Xamarin.iOS and Xamarin.Mac: Libraries that wrap native Apple APIs you can use to build apps for iOS and macOS using C# and Visual Studio
  • Xamarin.Android: A library that wraps native Java and Google APIs you can use to build apps for Android using C# and Visual Studio
  • Xamarin.Forms: An open-source library that allows you to share code across platforms and build apps that run on Android, iOS, and Windows from a single C# codebase

The biggest benefit of Xamarin.Forms is that you write code once and it will run on all the supported platforms at no additional cost. As you’ll learn throughout this e-book, Xamarin.Forms consists of a layer that wraps objects common to all the supported platforms into C# objects. Accessing native, platform-specific objects and APIs is possible in several ways, all discussed in the next chapters, but requires some extra work. Additionally, Xamarin integrates with the Visual Studio for Mac IDE, as well as with Visual Studio 2017 on Windows, so you can not only create cross-platform solutions, but also write code on different systems.

The Xamarin offering also includes Xamarin University, a paid service that allows you to attend live classes online and watch instructional videos that will help you prepare to get the Xamarin Certified Mobile Developer badge. It also includes the Xamarin Test Cloud service for test automation. Microsoft has also recently started the Visual Studio App Center, a complete cloud solution for the app management lifecycle from build automation to continuous integration, tests, analytics, and much more (note that Internet Explorer is not supported). This e-book focuses on Xamarin.Forms and targets Visual Studio for Mac, but if you prefer working on Windows, you can download the Xamarin.Forms Succinctly 2nd edition e-book from the same author. I have also recorded a video series for Syncfusion that provides an overview of Xamarin, Xamarin.iOS, and Xamarin.Android, as well as Xamarin.Forms.

Setting up the development environment

In order to build native mobile apps with Xamarin.Forms and Visual Studio for Mac, you need to configure your Mac machine for development. Actually, the same steps apply to both Xamarin.iOS and Xamarin.Forms. Configuring the Mac can be divided into two steps: installing Apple tools, and installing Microsoft Visual Studio for Mac.

Installing Apple Developer Tools and SDKs

In order to configure you Mac for developing apps with Xamarin.Forms and Visual Studio for Mac, you must satisfy the following requirements:

  • Your Mac must run macOS “Sierra” (10.12) or higher.
  • You must install Xcode 9, the Apple’s IDE, and Apple SDKs, which you get from the App Store for free. The download is approximately 5 Gb, so it will take some time to get it ready.

The reason you need Xcode is simple: Apple’s policies establish that only Xcode can generate and sign iOS app packages; therefore, tools such as Visual Studio for Mac will need to invoke Xcode and the Apple SDKs behind the scenes to generate and sign your app binaries. When Xcode has been installed, you should at least create and run a new blank project, so that Xcode will generate all the necessary files for development. The official Xamarin documentation has a specific page that will help you configure a Mac computer, and I recommend you read it carefully, especially because it explains how to configure profiles and certificates, and how to use Xcode to perform preliminary configurations. Actually, the documentation is about Xamarin.iOS, but the same steps apply to Xamarin.Forms.

Installing Visual Studio for Mac

Visual Studio for Mac is available in three editions: Enterprise, Professional, and Community. Enterprise and Professional are available through MSDN subscriptions, whereas the Community edition can be downloaded for free, and is enough to successfully complete all the examples in this eBook.

The first screen of the installer looks like the one shown in Figure 1. All available components are already installed on my Mac, so in Figure 1 the checkboxes are disabled, but in your case, they will likely all be enabled.

Installing Xamarin development tools

Figure 1: Installing Xamarin development tools

Make sure you select at least the Android + Xamarin.Forms and iOS + Xamarin.Forms components. .NET Core will not be discussed in this e-book, so installing it is totally up to you. Optionally, you might select Workbooks & Inspector, two interesting diagnostic tools summarized shortly. When you’re ready, click Done. At this point, the installer will take care of downloading and installing all the necessary tools to build apps for Android and iOS (see Figure 2).

The VS for Mac installation progress

Figure 2: The VS for Mac installation progress

Wait for the installation to complete, and keep in mind that it might take some time.

Creating Xamarin.Forms solutions

Assuming that you have installed and configured your development environment, the next step is opening Visual Studio to see how you create Xamarin.Forms solutions, and what these solutions consist of. Project templates for Xamarin.Forms are available in the Multiplatform > App node of the New Project dialog (see Figure 3).

Project templates for Xamarin.Forms

Figure 3: Project templates for Xamarin.Forms

The Forms App template can be used to scaffold a Xamarin.Forms solution that includes a number of pages and sample data, and is useful to understand concepts such as navigation and data-binding. The Blank Forms App template allows you to create a completely blank Xamarin.Forms solution, and I will be using this template to discuss all the next topics. Other templates are related to native and game development and will not be discussed in this e-book.

Select the Blank Forms App template, and then click Next. At this point, Visual Studio will ask you to specify some information (see Figure 4). More specifically, in the App Name box you can enter the app name, and this name will also be used to generate a bundle identifier, which is the combination of the Organization Identifier and the App Name. A bundle identifier is an ID that uniquely represents your app package. By convention, the Organization Identifier is in the form com.yourorganizationname, where com. is a common prefix.

Providing basic information for a new app

Figure 4: Providing basic information for a new app

In the Target Platforms group, you can decide to target individual platforms or both Android and iOS. In the Shared Code group, you can choose between Shared Project and Portable Class Library. The code sharing strategy is a very important topic in Xamarin.Forms, and Chapter 2 will provide a detailed explanation. For now, select the Use Portable Class Library option and click Next. On the next screen, you will be asked to enter the project name and the solution name, and you will have an option to enable Git version control and Xamarin Test Cloud for automated UI tests, as shown in Figure 5. The project name is not relevant at this point, so enter one, and click Create.

Entering project and solution name

Figure 5: Entering project and solution name

Once the project has been created, in the Solution pad, you will see that the solution is made up of three projects, as demonstrated in Figure 6.

The structure of a Xamarin.Forms solution

Figure 6: The structure of a Xamarin.Forms solution

The first project is either a Portable Class Library or a Shared Project, depending on your selection at project creation. This project contains all the code that can be shared across platforms, and its implementation will be discussed in the next chapter. For now, what you need to know is that this project is the place where you will write all the user interface of your app, and all the code that does not require interacting with native APIs.

The second project, whose suffix is Droid, is a Xamarin.Android native project. It has a reference to the shared code and to Xamarin.Forms, and implements the required infrastructure for your app to run on Android devices. The third project, whose suffix is iOS, is a Xamarin.iOS native project. This one also has a reference to the shared code and to Xamarin.Forms, and implements the required infrastructure for your app to run on the iPhone and iPad. I will now provide more details on each platform project, so that you have a basic knowledge of their properties. This is very important, because you will need to fine-tune project properties every time you create a new Xamarin.Forms solution.

The Xamarin.Forms library

Technically speaking, Xamarin.Forms is a .NET library that exposes all the objects discussed in this e-book through a root namespace called Xamarin.Forms. It has been recently open sourced, and it ships as a NuGet package that Visual Studio automatically installs to all projects when you create a new solution. The NuGet Package Manager in Visual Studio will then notify you of available updates. Because creating Xamarin.Forms solutions must be allowed even if your PC is offline, Visual Studio installs the version of the NuGet package in the local cache, which isn’t typically the latest version available. For this reason, it is recommended that you upgrade the Xamarin.Forms and other Xamarin packages in the solution to the latest version, and, obviously, it is also recommended you only upgrade to stable releases. Though alpha and beta intermediate releases are often available, their only intended use is for experimenting with new features still in development. As of this writing, version 2.4.0.74863 is the latest stable release.

The Xamarin.Android project

Xamarin.Android makes it possible for your Xamarin.Forms solution to run on Android devices. The MainActivity.cs file represents the startup activity for the Android app that Xamarin generates. In Android, an activity can be thought of as a single screen with a user interface, and every app has at least one. In this file, Visual Studio adds startup code that you should not change, especially the initialization code for Xamarin.Forms you see in the last two lines of code. In this project, you can add code that requires accessing native APIs and platform-specific features, as you will learn in Chapter 8. The Resources folder is also very important, because it contains subfolders where you can add icons and images for different screen resolutions. The name of such folders starts with drawable, and each represents a particular screen resolution. The Xamarin documentation explains thoroughly how to provide icons and images for different resolutions on Android. In order to build the Android app package, you will need to specify the version of the Android SDK that Visual Studio should use. This can be accomplished in the Project Options dialog, which you enable by right-clicking the project name in the Solution pad and then selecting Options. In the Android Application tab (see Figure 7), you will be able to select the SDK version.

Selecting the version of the Android SDK for compilation

Figure 7: Selecting the version of the Android SDK for compilation

Visual Studio automatically selects the highest version available on your machine. This does not affect the minimum version of Android you want to target; it is related to the version of the build tools that Visual Studio will use. My recommendation is to leave the default selection unchanged.

Tip: You can manage installed SDK versions with the Android SDK Manager, a tool you can launch from Visual Studio by selecting Tools > SDK Manager.

In the same tab, you can also edit the so-called Android manifest. Here you specify your app’s metadata, such as name, version number, icon, and permissions the user must grant to the application. In Figure 7, you can see the list of permissions at the bottom of the dialog. The information you supply in the Android manifest is also important for publication to Google Play. For example, the package name uniquely identifies your app package in the Google Play store and, by convention, it is in the following form: com.companyname.appname, which is self-explanatory (com. is a conventional prefix). The version name is your app version, whereas version number is a single-digit string that represents updates. For instance, you might have version name 1.0 and version number 1, version name 1.1 and version number 2, version name 1.2 and version number 3, and so on.

The Install location option allows you to specify whether your app should be installed only in the internal storage or if memory cards are allowed, but remember that, starting from Android 6.0, apps can no longer be installed onto a removable storage. In the Minimum Android version dropdown menu, you can select the minimum Android version you want to target.

It is important to pay particular attention to the Required permissions list. Here you must specify all the permissions that your app must be granted in order to access resources such as the Internet, the camera, other hardware devices, sensors, and more. Remember that, starting from Android 6.0, the operating system will ask the user for confirmation before accessing a resource that requires one of the permissions you marked in the manifest, and the app will crash if it attempts to access a sensitive resource, but the related permission was not selected in the manifest.

In the Android Build tab of the Project Options dialog, you will be able to manage debugging and build options. I will not walk through all the available options here, but it’s worth highlighting the Use Fast Deployment option, which is enabled by default. When enabled, deploying the app to a physical or emulated device will only replace changed files. This can often cause the app not to work properly or not to start at all, so my recommendation is to disable this option.

The Xamarin.iOS project

Similar to the Xamarin.Android project, the Xamarin.iOS project makes it possible for your Xamarin.Forms solutions to run on the iPhone and iPad. Here the AppDelegate.cs file contains the Xamarin.Forms initialization code, and should not be changed. You can add all the code that requires accessing native APIs and platform-specific features in this project, as you will learn in Chapter 8. In the Info.plist file (see Figure 8), with each tab you can configure your app metadata, the minimum target version, supported devices and orientations, capabilities (such as Game Center and Maps integration), visual assets such as launch images and icons, and other advanced features.

The Info.plist file

Figure 8: The Info.plist file

The Info.plist file represents the app manifest in iOS, and therefore is not related to only Xamarin.iOS. In fact, if you have experience with Apple Xcode and native iOS development, you already know this file. Unlike Android, the iOS operating system includes restriction policies that are automatically applied to most sensitive resources, especially those involving security and privacy. Also, there are differences among iOS 8.x, 9.x, and 10.x in how the OS handles these options. The Info.plist reference will help you understand how to properly configure any exceptions. Among the project properties, the most important is, without a doubt, the iOS Bundle Signing, which you find in the same-named tab of the Project Options dialog (see Figure 9). You use bundle signing to specify the identity that the Apple tools must use to sign the app package, and specify the provisioning profile that is used to associate a team of developers to an app identifier. Configuring signing identities and profiles is particularly important when preparing an app for publishing.

The iOS Bundle Signing options

Figure 9: The iOS Bundle Signing options

Further details about configuring a Xamarin.iOS project are offered through the documentation.

Debugging and testing applications locally

Starting apps that you build with Xamarin.Forms for debugging and testing could not be easier: you simply select one of the platform projects in Solution Explorer as the startup project, then you select the target device and press Command + Enter. Do not forget to rebuild your solution before debugging for the first time. When you start an app for debugging, Visual Studio will build your solution and deploy the app package to the selected physical device or emulator. The result of the build process is an .apk file for Android, and an .ipa file for iOS. When the app starts either on a physical device or on an emulator, Visual Studio attaches an instance of the debugger, and you will be able to use all the powerful debugging tools of the IDE, including (but not limited to) breakpoints, data tips, tool windows, watch windows, and more. The easiest way to select the target platform and configuration is by using the standard toolbar, which you can see in Figure 10.

Selecting target platform and devices for debugging

Figure 10: Selecting target platform and devices for debugging

The Debug configuration is the appropriate choice during development, whereas Ad-Hoc is appropriate when preparing for distribution on both iOS and Android. When working with iOS, the target architecture is normally iPhoneSimulator for debugging an app in the iOS Simulator, or iPhone for debugging an app on a physical iPhone or iPad (remember that a physical Apple device must be associated to your Mac via Xcode and connected to the Mac). You can also quickly select the startup project and specify the target device. For example, in Figure 10 you can see a list of Android emulator configurations.

Note: In this e-book, I will provide figures that show all the supported platforms in action when it is relevant to do so. In other cases, I will show just one platform in action, meaning that the same behavior is expected on all platforms.

Figure 11 shows the previously created blank app running on both platforms within the respective emulators. Notice how, in the background, Visual Studio shows the Output window, where you receive messages from the debugger. You will be able to use all the other debugging tools similarly.

An app built with Xamarin.Forms running on all platforms

Figure 11: An app built with Xamarin.Forms running on all platforms

Running apps on physical devices

Visual Studio can easily deploy an app package to physical iOS and Android devices. For Android, you first need to enable the developer mode, which you accomplish with the following steps:

  1. Open the Settings app.
  2. Tap the About item.
  3. In the list that appears, locate the OS build number and tap this item seven times.

At this point, you can simply plug your device into the USB port of your PC, and Visual Studio will immediately recognize it. It will be visible in the list of available devices that you can see in Figure 10. For iOS, you’ll first need to connect your iPhone or iPad to your Mac computer, making sure you make them discoverable through Xcode. Then, when you start debugging from Visual Studio, your app will be deployed to the iPhone or iPad.

Analyzing and profiling applications

The Xamarin toolbox has been recently enriched with three amazing tools: Xamarin Workbooks, Xamarin Inspector, and Xamarin Profiler. The first tool allows you to explore a number of .NET and Mono development platforms with interactive examples. The Xamarin Inspector allows you to nicely inspect the visual tree of your Xamarin apps and make changes to the UI in real time (see the documentation).

The Xamarin Profiler is a complete suite of analysis tools in one program that you can use to profile your mobile apps and analyze performance, memory usage, CPU consumption, and more. In Visual Studio, you can select Run > Start Profiling, and then you will be asked to specify what kind of analysis you want to execute against the application. Figure 12 shows an example based on the memory allocation analysis tool.

Analyzing app performance with Xamarin Profiler

Figure 12: Analyzing app performance with Xamarin Profiler

You can also take and compare snapshots of the memory in different moments to see if memory allocation can cause potential problems. This is an excellent performance analysis tool, and the documentation will provide all the details you need to improve your app performance.

Chapter summary

This chapter introduced the Xamarin.Forms platform and its goals, describing the required development tools and offering an overview of a Xamarin.Forms solution, passing through the platform projects and their most important settings. You have also seen how to start an app for debugging using emulators. Now that you have an overview of Xamarin.Forms and the development tools, the next step is understanding what is at its core: sharing code across platforms.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.