Reader small image

You're reading from  Cross-platform UI Development with Xamarin.Forms

Product typeBook
Published inAug 2015
Reading LevelBeginner
Publisher
ISBN-139781784391195
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Paul Johnson
Paul Johnson
author image
Paul Johnson

Paul Johnson has been writing software since the early 1980s on machines ranging from the ZX81 and servers to his trusty Mac, and has used more languages than he can remember. He is a qualified scuba diver and college lecturer. Paul lives with his wife, kids, and pets, and listens to an inordinate amount of rock and metal on Primordial Radio. This is his third book for Packt.
Read more about Paul Johnson

Right arrow

Chapter 13. Social Media into the Mix

Social media (such as Facebook, Google+, and Twitter) forms an ever increasingly important role in a user and developer's life. Adding some form of social media in an app is not difficult, but it does pose a few issues. Add into the mix the networks that are not always possible to connect to, and it can be appreciated that things can become messy quickly.

In this chapter, we will:

  • Learn how to test for network connectivity

  • Connect to Facebook and Twitter in an app

Connect me up, Scotty


By default, Xamarin Forms has no way of knowing if a phone has a network connection. But then, why should it? Remember that anything hardware-specific has to be handled by the hardware. This means that we need to use injection.

There is a package on NuGet that allows you to check on connectivity, but it is more interesting to see how we can do it without relying on additional packages.

To start with, we need to decide on the best way to do this. We can use an event or an interface. In general, listening in on an event is simple. The PCL listens for an event generated from the platform.

This was easy. Wow! This is going to be a short chapter!

Except that it isn't. The problem is not so much the change in the network state; it's more in getting the initial state. In this case, we will use the standard interface or the injection method.

Setting up the event system and interface


The interface only needs to be something as simple as the following code:

namespace connectivity
{
  public interface IConnectivity
  {
    bool NetworkConnected();
  }
}

Note

The source for the connectivity part of the chapter can be found in Chapter13/Connectivity.

To track the state of the connection, a bool variable is set up in App:

public static App Self {get; private set;}

public bool IsConnected {get; private set;}

public App()
{
  App.Self = this;
  IsConnected = DependencyService.Get<IConnectivity>().NetworkConnected();

The reason why IsConnected is set to private set; is because the listener for the event change is in App. We will keep all the connectivity parts in one place.

The handler for the event is also fairly simple, although we need to also broadcast back to the platform to send an internal notification, as shown in the following code:

public UIChangedEvent MessageEvent { get; set;}
MessageEvent = new UIChangedEvent();

MessageEvent...

Setting up your Android code


Setting up the connectivity code in Android is a two-step procedure:

  1. The first is the creation of BroadcastReceiver.

  2. The second is calling this receiver into being.

Broadcast whatcha-ma-call-it?

When something happens on the hardware level, Android broadcasts a message that any code can listen to. In order to listen to the message, a broadcast receiver is used. In the case of the connectivity broadcast receiver, the code is simple enough:

[BroadcastReceiver]
public class Connectivity : BroadcastReceiver
{
  public override void OnReceive(Context context, Intent intent)
  {
    var extras = intent.Extras;
    
    using (var info = extras.GetParcelable("networkInfo") as NetworkInfo)
    {
      var state = info.GetState();
      
      var result = state == NetworkInfo.State.Connected || state == NetworkInfo.State.Connecting;
      
      // store the online state in the internal settings system
      
      ConfigUtils.SaveSetting("online", result, SettingType.Bool...

Setting up iOS


iOS is very simple to set up and listens for events. The basis for the majority of code is based on the freely available Reachability.cs class from Xamarin (https://github.com/xamarin/monotouch-samples/blob/master/ReachabilitySample/reachability.cs).

This class contains just about everything required to check your connection. In AppDelegate.cs, a small amount of code is needed to get the ConnectionChanged event:

// set up notifications
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);

// produce notification
MessageEvents.Change += (object s, UIChangedEventArgs ea) =>
{
  if (ea.ModuleName == "Notification")
  {
    var notification = new UILocalNotification
    {
      FireDate = DateTime.Now,
      AlertAction = "Connection changed",
      AlertBody = ea.Info,
    };
    UIApplication.SharedApplication...

Setting up Windows Phone


Setting up the change of connectivity is simple on Windows Phone. In MainPage.xaml.cs, we need to subscribe to the NetworkAvailablityChanged event as follows:

DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(ChangeDetected); 

The ChangeDetected event is also simple, as shown in the following code:

void ChangeDetected(object sender, NetworkNotificationEventArgs e)
{
  MessageEvents.BroadcastIt("Connection",
  e.NotificationType==NetworkNotificationType.InterfaceConnected ?
  true.ToString() : false.ToString());
}

Finally, we need to implement the interface:

void ChangeDetected(object sender, NetworkNotificationEventArgs e)
{
  MessageEvents.BroadcastIt("Connection",
  e.NotificationType==NetworkNotificationType.InterfaceConnected ?
  true.ToString() : false.ToString());
}
class Connection : IConnectivity
{
  public bool NetworkConnected()
  {
    var rv = false;
    try
    {
      var InternetConnectionProfile...

Adding social media to your app


Social media sites (such as Facebook and Twitter) are fast becoming the defacto method of communication for people around the world. They both have massive advantages over sending messages with images via MMS or have the text size restrictions that are found in text messaging.

Adding social media in an app is not that difficult and works via a login system that passes the information to either the OAuth1 or OAuth2 authentication system for verification.

The difference between OAuth and OAuth2

OAuth2 gives the mobile developer a lot of advantages over the original version. One of the most important advantages is that OAuth2 doesn't require the app to launch a web page for authentication. The second advantage is that the OAuth2 token is short-lived: the app cannot stay live forever.

Implementing OAuth

We can implement OAuth in a number of ways. The simplest way is to install Xamarin.Auth via NuGet (at the time of writing, the component store only lists this for iOS...

OAuth1 for Twitter


Note

The source for this part can be found in Chapter13/Twitter.

In order to get this part to work, you will first need to register an app. This gives you a key that is required as part of the authentication system.

To register an app, perform the following steps:

  1. You will need to go to https://apps.twitter.com and click on the Create an application button.

  2. You will need to fill in the requested information.

  3. Once filled, scroll down to the bottom of the screen, agree to the terms, and click on Create your Twitter application.

    Note

    The source for this part can be found in Chapter13/Twitter.

  4. Once you have created your app, you will be taken to a details page that will look similar to the following screenshot:

  5. You will need to generate an access token. You will find this by clicking on the Keys and Access Tokens tab. At the bottom of the screen, you will find a button to generate the token. Click on the button to generate your access token.

  6. Your app will need the API Key, API Secret...

Using OAuth2


As with Twitter, we will use the Xamarin.Auth package.

The Facebook example in this chapter will need you to first register for the Facebook app and then add a new app. When presented with the option of what to target, select the Advanced option. This allows you to target all the platforms at once. This will give you a secret app ID that is required for OAuth2. You will also need to go to Settings | Advanced, part way down under Client OAuth Redirect, and enter the redirecting URL. This can be any URL that exists for testing purposes. Once the app is ready for the bigger picture, the redirect page should be a page of a website that is not publically accessible.

Note

The source for this part can be found in Chapter13/Facebook.

Virtually, the same code that was used for Twitter can be used for Facebook, but with OAuth2 and not OAuth1. The authenticator looks similar to the following code:

var auth = new OAuth2Authenticator(
clientId: "APP_ID",
scope: "", // permissions
authorizeUrl...

The user interface


It is worth pointing out here that the UI is not what you would expect. Most often, with a Xamarin Forms application, the UI is constructed from the PCL. Moreover, the likes of Facebook and Twitter provide their own login user interface. This is part of the remit of OAuthAuthenticator.

This means that the PCL UI for the content page is empty, and we rely on a custom renderer to produce the user interface with a callback to the PCL once the login has been performed.

A very simple implementation of a Facebook login (as supplied with the example code for this chapter) looks similar to the following screenshot when executed. The example is using the Windows Phone emulator under the Windows directory, but the same UI is produced for Android and iOS.

The reason why the UI is the same for the login is that it is supplied by Facebook as an embedded web page through the authenticator service.

Summary


There is nothing difficult in logging in to a social media source. It provides a very simple and effective method to log in to your app without the problems of writing your own login system; simply grab the token returned, store it on the server, and compare it on successive logins.

There are some sticking points for the flow, but nothing too terrible.

In the next and final chapter we'll tie up the loose ends and by the end of it, you will have all the tools required to create your own Xamarin Forms app. Hang on…. it's going to be the ride of a lifetime!

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Cross-platform UI Development with Xamarin.Forms
Published in: Aug 2015Publisher: ISBN-13: 9781784391195
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
Paul Johnson

Paul Johnson has been writing software since the early 1980s on machines ranging from the ZX81 and servers to his trusty Mac, and has used more languages than he can remember. He is a qualified scuba diver and college lecturer. Paul lives with his wife, kids, and pets, and listens to an inordinate amount of rock and metal on Primordial Radio. This is his third book for Packt.
Read more about Paul Johnson