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 8. Contacts, Camera, and Location

Some of the most vital features used by mobile applications today are based on the new types of data that can be collected by our devices. Features such as a device's GPS location and camera are staples in modern applications such as Instagram or Twitter. It's difficult to develop an application and not use some of these functionalities. So, let's explore our options for taking advantage of this functionality with Xamarin.

In this chapter, we will do the following:

  • Introduce the Xamarin.Mobile library

  • Read the address book on Android and iOS

  • Retrieve the GPS location of our device

  • Pull photos from the camera and photo library

Introducing Xamarin.Mobile


To simplify the development of these features across multiple platforms, Xamarin has developed a library called Xamarin.Mobile. It delivers a single API for accessing the contacts, GPS location, heading of the screen, camera, and photo library for iOS, Android, and even Windows platforms. It also takes advantage of Task Parallel Libraries (TPL) to deliver a modern C# API that will make developers more productive than their native alternatives would. This gives you the ability to write nice, clean, asynchronous code using the async and await keywords in C#. You can also reuse the same code in iOS and Android, apart from a few differences that are required by the Android platform.

To install Xamarin.Mobile, open the Xamarin Component Store in Xamarin Studio and add the Xamarin.Mobile component to a project, as shown in the following screenshot:

Before we dig further into using Xamarin.Mobile, let's review the namespaces and functionality available with the library...

Accessing contacts


To begin our exploration of what Xamarin.Mobile offers, let's access the address book within a Xamarin application. Let's improve the add friend feature of XamSnap by loading friends from the user's contact list. Make sure to add Xamarin.Mobile to the project from the Component Store for both the iOS and Android projects.

Navigate to the XamSnap portable class library. First, we will need to split apart the IWebService interface, by moving one method to a new IFriendService interface:

public interface IFriendService 
{ 
    Task<User[]> GetFriends(string userName); 
} 

Next, in FriendViewModel, we will need to use the new IFriendService interface instead of the old one:

private IFriendService friendService =  
  ServiceContainer.Resolve<IFriendService>(); 
 
public async Task GetFriends() 
{ 
  //previous code here, use 'friendService' instead of 'service' 
  Friends = await friendService.GetFriends(settings.User...

Looking up GPS location


Using Xamarin.Mobile to track a user's GPS location is as simple as accessing their contacts. There is a similar process for setting up access on iOS and Android, but in the case of location, you don't have to request permission from code. iOS will automatically show the standard alert requesting permission. Android, on the other hand, merely requires a manifest setting.

As an example, let's add functionality to our XamSnap application that tags GPS location to messages within a chat conversation. You can think of this as tagging a location to a photo, as in other apps. Make sure to add Xamarin.Mobile to the project from the Component Store.

First, let's implement a Location class for storing latitude and longitude:

public class Location
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

Next, let's add a Location property to the Message class:

public Location Location { get; set; }

Now, let's create a new ILocationService...

Accessing the photo library and camera


The last major feature of Xamarin.Mobile is the ability to access photos in order to give users the ability to add their own content to your applications. Using a class called MediaPicker, you can pull photos from the device's camera or photo library and optionally display your own UI for the operation.

Let's modify MessageViewModel to support photos. First, add the following property:

public string Image { get; set; } 

Next, we need to modify the following lines in the SendMessage method:

if (string.IsNullOrEmpty(Text) && string.IsNullOrEmpty(Image))
   throw new Exception("Message is blank.");
 
//Then further down 
var message = await service.SendMessage(new Message
{
     UserName = settings.User.Name,
     Conversation = Conversation.Id,
     Text = Text,
     Image = Image,
     Location = location,
});
//Clear our variables 
Text =
      Image = null;  

Next...

Summary


In this chapter, we discovered the Xamarin.Mobile library and how it can accelerate common tasks in a cross-platform way. We retrieved contacts from the address book and set up GPS location updates over time. Lastly, we loaded photos from the camera and photo library.

After completing this chapter, you should have a complete grasp of the Xamarin.Mobile library and the common functionality it provides for cross-platform development. It gives clean, modern APIs that offer async/await functionality that can be accessed across iOS, Android, and Windows Phone. Accessing contacts, GPS, and photos across platforms is very straightforward with Xamarin.Mobile.

In the next chapter, we'll create a real web service using Windows Azure to drive our XamSnap application. We will use a feature called Azure Functions and implement push notifications on iOS and Android.

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 €14.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