Xamarin Guide 5. Add ShareService

Scope

This Xamarin Workshop Guide was created for the The Portuguese National Meeting of IT Students (ENEI) by Sara Silva which original content is available here. With the goal to extend it to the global community, it was published in a new project called Xam Community Workshop, which the main goal is to any developer, or user group customize it to theirs events.

Guides 5. Add ShareService

An application which allow to share content in social networks brings more value to the users, because allow to share with others something the user think is important or relevant. An application for events like 1010 ENEI Sessions App could not miss this feature.

Each platform has your own implementation to share content in social network. This means, we need to create an abstraction of the share feature to use it in ENEI.SessionsApp and then in each platform we need to implement that abstraction. Let’s see how the Abstraction Pattern can be created! In ENEI.SessionsApp project, create the interface IShareService as following:

public interface IShareService 
{ 
void ShareLink(string title, string status, string link); 
}

Then is required to create the implementation of the IShareService in each platform. Let’s define the following implementation by platform:

Windows Phone

[assembly: Dependency(typeof(ShareService))]
namespace ENEI.SessionsApp.WinPhone.Services
{
    public class ShareService : IShareService
    {
      public void ShareLink(string title, string status, string link)
      {
        var task = new ShareLinkTask { Title = title, Message = status, LinkUri = new Uri(link) };
        Device.BeginInvokeOnMainThread(() =>
        {
            try
            {
                task.Show();
            }
            catch (Exception ex)
            {
             // todo handle the error   
            }
        });
    }
  }
}

Android

 [assembly: Dependency(typeof(ShareService))]
 namespace ENEI.SessionsApp.Droid.Services
 {
   public class ShareService : IShareService
   {
     public void ShareLink(string title, string status, string link)
     {
        var intent = new Intent(global::Android.Content.Intent.ActionSend);
        intent.PutExtra(global::Android.Content.Intent.ExtraText, string.Format("{0} - {1}", status ?? string.Empty, link ?? string.Empty));
        intent.PutExtra(global::Android.Content.Intent.ExtraSubject, title ?? string.Empty);
        intent.SetType("text/plain");
        intent.SetFlags(ActivityFlags.ClearTop);
        intent.SetFlags(ActivityFlags.NewTask);
        Android.App.Application.Context.StartActivity(intent);
    }
  }
}

iOS

[assembly: Dependency(typeof(ShareService))]
namespace ENEI.SessionsApp.iOS.Services
{
public class ShareService : IShareService
{
    public void ShareLink(string title, string status, string link)
    {
        var actionSheet = new UIActionSheet("Share on");
        foreach (SLServiceKind service in Enum.GetValues(typeof(SLServiceKind)))
        {
            actionSheet.AddButton(service.ToString());
        }
        actionSheet.Clicked += delegate(object a, UIButtonEventArgs b)
        {
            SLServiceKind serviceKind = (SLServiceKind)Enum.Parse(typeof(SLServiceKind), actionSheet.ButtonTitle(b.ButtonIndex));
            ShareOnService(serviceKind, title, status, link);
        };
        actionSheet.ShowInView(UIApplication.SharedApplication.KeyWindow.RootViewController.View);
    }

    private void ShareOnService(SLServiceKind service, string title, string status, string link)
    {
        if (SLComposeViewController.IsAvailable(service))
        {
            var slComposer = SLComposeViewController.FromService(service);
            slComposer.SetInitialText(status);
            slComposer.SetInitialText(title != null ? string.Format("{0} {1}", title, status) : status);
            if (link != null)
            {
                slComposer.AddUrl(new NSUrl(link));
            }
            slComposer.CompletionHandler += (result) =>
            {
                UIApplication.SharedApplication.KeyWindow.RootViewController.InvokeOnMainThread(() =>
                {
                    UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
                });
            };
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(slComposer, true, null);
        }
    }
  }
}

This way, we are ready to call the share service in the SessionsView using DependencyService, as following: private void ShareGesture_OnTapped(object sender, EventArgs e) { var tappedEventArg = e as TappedEventArgs; if (tappedEventArg != null) { var session = tappedEventArg.Parameter as Session; if (session != null) { var shareService = DependencyService.Get(); if (shareService != null) { var status = string.Format(“Não percas a sessão {0} de {1}.”, session.Name, session.Speaker.Name); shareService.ShareLink(“ENEI 2015”, status, “https://enei.pt/”); } } } }

The DependencyService only will get the implementation from the IShareService because the implementation from each platform was registered using: [assembly: Dependency(typeof(ShareService))]

At this moment the 1010 ENEI Sessions App has support to share session in social network!