Implementing social media sharing in Ionic applications

December 27, 2016, 1:32 pm Categories:

Categories

What is content without an audience?

** UPDATED FOR IONIC 3 **

In today's hyper-connected world our applications rely heavily on how our audience can interact with and use the content contained within them. Whether you're developing the latest game, informational resource or something humorous users expect to be able to do more than just passively consume that content.

Nowhere is this more true than with the rise of social media over the last decade.

With the ability to share content ranging from text, images, links and video to embedding data feeds and even creating full blown applications based exclusively on social media content user expectations have risen.

As a developer/business capturing your user's attention, generating interest in your application, retaining your audience and even getting them to freely market your product(s)/service(s) via social media is now, or should be, part and parcel of the whole development planning cycle.

One of the ways in which we can facilitate such functionality in our Ionic apps is through Eddy Verbruggen's excellent social sharing plugin for Apache Cordova/PhoneGap which is supported on the following platforms:

  • iOS 6+
  • Android 2.3.3+
  • Windows Phone 8 (possibly WP7 too - but that is, as yet, unconfirmed)

So, with that level of support, there are no problems using this in our Ionic apps.

Over the course of the following tutorial we'll use this plugin to develop a simple one-page application that allows us to share an image and, across supporting social media platforms, text and a URL through the following:

  • Facebook
  • Instagram
  • Twitter
  • E-mail
  • System modal options

Our app will resemble the following (your content will, of course, vary to mine):

Ionic app with social sharing functionality implemented

Building our app

In your command line utility (I.e. Terminal for Mac OS X or Command Prompt for Windows) run the following command to create the initial foundations for the Social Sharing app:

ionic start social-sharing blank

Upon being successfully created change into the root of the app directory:

cd social-sharing

And complete the initial application set-up by installing the Social Sharing plugin:

ionic plugin add cordova-plugin-x-socialsharing

With the plugin successfully installed and the bare bones foundation for our app in place we can now turn our attention to implementing the necessary TypeScript and HTML.

Application logic

Thankfully the coding required for our social sharing app is fairly minimal and quick to implement as many of the methods will simply mirror one another in terms of syntax and functionality.

Open and amend your social-sharing/src/pages/home/home.ts script so that it resembles the following example:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { SocialSharing } from 'ionic-native';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
	
   public sendTo   : any; 
   public subject  : string = 'Message from Social Sharing App';
   public message  : string = 'Take your app development skills to the next level with Mastering Ionic - the definitive guide';
   public image    : string	= 'http://masteringionic2.com/perch/resources/mastering-ionic-2-cover-1-w320.png';
   public uri      : string	= 'http://masteringionic2.com/products/product-detail/s/mastering-ionic-2-e-book';


   constructor( public navCtrl    : NavController,
                public platform   : Platform) 
   {
    
   }



   shareViaEmail()
   {
      this.platform.ready()
      .then(() => 
      {
         SocialSharing.canShareViaEmail()
         .then(() => 
         {
            SocialSharing.shareViaEmail(this.message, this.subject, this.sendTo)
            .then((data) =>
            {
               console.log('Shared via Email');
            })
            .catch((err) =>
            {
               console.log('Not able to be shared via Email');
            });
         })
         .catch((err) =>
         {
            console.log('Sharing via Email NOT enabled');
         });
      });
   }
  	


   shareViaFacebook()
   {
      this.platform.ready()
      .then(() => 
      {
         SocialSharing.canShareVia('com.apple.social.facebook', this.message, this.image, this.uri)
         .then((data) =>
         {

            SocialSharing.shareViaFacebook(this.message, this.image, this.uri)
            .then((data) =>
            {
               console.log('Shared via Facebook');
            })
            .catch((err) =>
            {
               console.log('Was not shared via Facebook');
            });

         })
         .catch((err) =>
         {
            console.log('Not able to be shared via Facebook');
         });

      });
   }




   shareViaInstagram()
   {
      this.platform.ready()
      .then(() => 
      {
		
         SocialSharing.shareViaInstagram(this.message, this.image)
         .then((data) =>
         {	
            console.log('Shared via shareViaInstagram');
         })
         .catch((err) =>
         {
            console.log('Was not shared via Instagram');
         });

      });
   }




   sharePicker()
   {
      this.platform.ready()
      .then(() => 
      {		  		

         SocialSharing.share(this.message, this.subject, this.image, this.uri)
         .then((data) =>
         {
            console.log('Shared via SharePicker');
         })
         .catch((err) =>
         {
            console.log('Was not shared via SharePicker');
         });

      });
   }




   shareViaTwitter()
   {
      this.platform.ready()
      .then(() => 
      {

         SocialSharing.canShareVia('com.apple.social.twitter', this.message, this.image, this.uri)
         .then((data) =>
         {

            SocialSharing.shareViaTwitter(this.message, this.image, this.uri)
            .then((data) =>
            {
               console.log('Shared via Twitter');
            })
            .catch((err) =>
            {
               console.log('Was not shared via Twitter');
            });

         });

      })
      .catch((err) =>
      {
         console.log('Not able to be shared via Twitter');
      });
   }



}

Breaking the above script down we begin by importing the required SocialSharing plugin:

import { SocialSharing } from 'ionic-native';

Without this we won't be able to access the plugin methods which provide the ability to share content via different social media platforms.

Such access will be conditionally based on the platform options we have configured (or not configured) in our mobile device settings (as demonstrated in the iOS device settings screen captures below):

Social media app settings on iOS 9

Towards the top of our TypeScript class we then create public properties - assigning to those the necessary content that we wish to share through social media:

public sendTo   : any; 
public subject  : string 	= 'Message from Social Sharing App';
public message  : string 	= 'Take your app development skills to the next level with Mastering Ionic - the definitive guide';
public image    : string	= 'http://masteringionic2.com/perch/resources/mastering-ionic-2-cover-1-w320.png';
public uri      : string	= 'http://masteringionic2.com/products/product-detail/s/mastering-ionic-2-e-book';

Not all of these properties will be able to be used for each platform we target but by declaring them at the top of our class we make them available for use, where possible, in multiple methods without fear of duplication.

Declare once, re-use many times - always a nice principle to follow wherever possible.

After our class constructor we subsequently declare the following 5 methods:

  • shareViaEmail
  • shareViaFacebook
  • shareViaInstagram
  • sharePicker
  • shareViaTwitter

All of which utilise the SocialSharing plugin API to determine whether we can access a particular service or system functionality and then, if positive, attempts to post content to those services.

Each method is essentially a carbon copy of the preceding method; the only real variation, aside from some slight syntax changes, is that of targeting a different social media platform or device service.

We begin each method by using the platform.ready() method to ensure our plugin can access the device API followed by the SocialSharing plugin methods which returns data in the form of a Promise:

shareViaFacebook()
{
   this.platform.ready()
   .then(() => 
   {
      SocialSharing.canShareVia('com.apple.social.facebook', this.message, this.image, this.uri)
      .then((data) =>
      {
         SocialSharing.shareViaFacebook(this.message, this.image, this.uri)
         .then((data) =>
         {
            console.log('Shared via Facebook');
         })
         .catch((err) =>
         {
            console.log('Was not shared via Facebook');
         });

      })
      .catch((err) =>
      {
         console.log('Not able to be shared via Facebook');
      });

   });
}

In each method we simply use console logs to 'echo' out the success or failure of attempting to execute the method. We could of course enhance this and make it more professional by, for example, using notifications courtesy of the ToastController component.

Application markup

With the logic for the application in place open the social-sharing/src/pages/home/home.html file and implement the following markup:

<ion-header>
   <ion-navbar>
      <ion-title>
         Social Share
      </ion-title>
   </ion-navbar>
</ion-header>

<ion-content padding>
  

   <ion-item>
      <img src="assets/images/mastering-ionic-2-book-cover-logos-snapshot.png">
      <caption>
         <h2>Mastering Ionic</h2>
         <p>The Definitive Guide</p>
      </caption>
   </ion-item>



   <ion-list>
      <ion-item-group class="group">
         <ion-item-divider color="light">Share through social media</ion-item-divider>
         <ion-item>
            <button
               class="button"  
               ion-button 
               icon-right 
               block 
               padding-vertical 
               color="primary" 
               (click)="shareViaFacebook()">
                  Share this via Facebook
                  <ion-icon ios="logo-facebook" md="logo-facebook"></ion-icon>
            </button>
         </ion-item>


         <ion-item>
            <button
               class="button"  
               ion-button 
               icon-right 
               block 
               padding-vertical 
               color="primary" 
               (click)="shareViaInstagram()">
                  Share this via Instagram
                  <ion-icon ios="logo-instagram" md="logo-instagram"></ion-icon>
            </button>
         </ion-item>


         <ion-item>
            <button 
               class="button"  
               ion-button 
               icon-right 
               block 
               padding-vertical 
               color="primary" 
               (click)="shareViaTwitter()">
                  Share this via Twitter
                  <ion-icon ios="logo-twitter" md="logo-twitter"></ion-icon>
            </button>
         </ion-item>


         <ion-item>
            <button
               class="button"  
               ion-button 
               icon-right 
               block 
               padding-vertical 
               color="primary" 
               (click)="sharePicker()">
                  Share this via Share Sheet
                  <ion-icon ios="ios-share" md="md-share"></ion-icon>
            </button>
         </ion-item>
      </ion-item-group>



      <ion-item-group class="group">
         <ion-item-divider color="light">Share via e-mail</ion-item-divider>
         <ion-item>
            <ion-label block>To: </ion-label>
            <ion-input 
               block 
               type="text" 
               placeholder="E-mail address..." 
               [(ngModel)]="sendTo"></ion-input>
         </ion-item>



         <ion-item>
            <button
               class="button"  
               ion-button 
               icon-right 
               block 
               padding-vertical 
               color="primary" 
               (click)="shareViaEmail()">
                  Share this via Email
                  <ion-icon ios="ios-mail" md="md-mail"></ion-icon>
            </button>
         </ion-item>
      </ion-item-group>

   </ion-list>

</ion-content>

Nothing terribly fancy or overly complex here; just an image accompanied by a caption with a series of Ionic UI components/buttons underneath, each of which call a specific method from our TypeScript class.

One thing to note with the Share via e-mail section is the presence of a text input field for entering a user's e-mail address. The value for this field binds to the sendTo model that we defined in the TypeScript class (we don't implement any validation here so the Share this via Email button can activate the native e-mail application without passing an e-mail address from this field - something we would NEVER do in a real world project).

Now save all of your code and, using the Ionic CLI, build the application for your selected platform (iOS, Android or Windows Phone), for example:

ionic build ios

After the build process has successfully completed, deploy and run the application on a mobile device connected to your desktop/laptop computer.

Once the application is up and running you should be able to access different social media platforms/device functionality, based on the methods we scripted, as demonstrated in the following screen captures (from left to right: Twitter, device sharing sheet and Instagram):

Twitter, generic sharing and Instagram access

In summary

Thanks to Ionic Native (and the awesome developers who contribute their time and effort to create such fantastic plugins) adding the ability to share content across different social media platforms is incredibly simple.

Such functionality is useful in helping to promote your products/services to a wider audience, across multiple platforms, and, as a side benefit, enabling your users to perform informal, ad-hoc marketing on your behalf.

As you can see adding such a simple feature to your app provides a lot of benefits in return - and with that we conclude this tutorial.

Feel free to use the above code in your own Ionic projects as you see fit and, if you're feeling generous, consider using the form below to leave a comment on this tutorial.

If you enjoyed what you've read here then please sign up to my mailing list and, if you haven't done so already, take a look at my e-book: Mastering Ionic for further projects and tutorials based on the Ionic framework.

Tags

Categories

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.

Top