Social sharing is one of the most important features that you should implement in your application, it helps you get more downloads to your application and also more people know about the app. With social media platforms like Facebook, Instegram and Twitter it's obvious to implement this functionality in your app.

For me I always add social sharing icons to my ionic applications and the Social Sharing helps me and make things easy for me. So let's get started and try to make this plugin work for us.

Installing Social Sharing Plugin

As always installing an ionic plugin is easy and simple you only need to run some command lines and that's it.

    ionic cordova plugin add cordova-plugin-x-socialsharing
    npm install --save @ionic-native/social-sharing

After installing this plugin you need to add it to array providers in app.module.ts of course you need to import it first just like this code bellow:

import { SocialSharing } from "@ionic-native/social-sharing";

  providers: [
    SocialSharing,
    ]

Ionic Social Sharing Plugin Example

Great! now that we have installed the ionic social sharing plugin, we need to make that plugin works and to do what it should do, that's why we need to generate a service provider, you only need to run this command line again in your terminal or command line.

ionic g provider social

Or in ionic 4

ionic g service services/social

That's it, now that we everything we need to make the ionic social sharing works there is one thing to do, we should implement functions that will be responsible for sharing in a specific social media platform. that's why you can copy and past this code bellow in your providers/social/social.ts file or for ionic 4 apps services/social/social.service.ts

import { Injectable } from '@angular/core';
import { ToastController, Platform} from 'ionic-angular';
import { SocialSharing } from '@ionic-native/social-sharing';

@Injectable()
export class SocialProvider {

    constructor(private socialSharing: SocialSharing,
                    private platform: Platform,
                    private toastCtrl: ToastController) {
      }

      share(packageName: string,
            appName: string,
            social: string,
            message: string,
            subject: string,
            image: string,
            url:string) {
          this.platform.ready().then(() => {
            if (social === "facebook") {
              this.socialSharing
                .canShareVia(
                  packageName,
                  message,
                  subject,
                  image,
                  url
                )
                .then(() => {
                  this.socialSharing
                    .shareViaFacebook(message, image, url)
                    .catch(err => {
                      this.showSuccesToast(
                        "There was a problem please try later"
                      );
                    });
                })
                .catch(err => {
                  this.showFailToast(appName);
                });
            } else if (social === "whatsapp") {
              this.socialSharing
                .canShareVia(
                  packageName,
                  message,
                  subject,
                  image,
                  url
                )
                .then(() => {
                  this.socialSharing
                    .shareViaWhatsApp(message, image, url)
                    .catch(err => {
                      this.showSuccesToast(
                        "There was a problem please try later"
                      );
                    });
                })
                .catch(err => {
                  this.showFailToast(appName);
                });
            } else if (social === "instagram") {
              this.socialSharing
                .canShareVia(
                  packageName,
                  message,
                  subject,
                  image,
                  url
                )
                .then(() => {
                  this.socialSharing
                    .shareViaInstagram(message, image)
                    .catch(err => {
                      this.showSuccesToast(
                        "There was a problem please try later"
                      );
                    });
                })
                .catch(err => {
                  this.showFailToast(appName);
                });
            } else if (social === "twitter") {
              this.socialSharing
                .canShareVia(
                  packageName,
                  message,
                  subject,
                  image,
                  url
                )
                .then(() => {
                  this.socialSharing
                    .shareViaTwitter(message, image, url)
                    .catch(err => {
                      this.showSuccesToast(
                        "There was a problem please try later"
                      );
                    });
                })
                .catch(err => {
                  this.showFailToast(appName);
                });
            } else {
              this.socialSharing
                .share(message, subject, image, url)
                .catch(err => {
                  this.showSuccesToast("There was a problem please try later");
                });
            }
          });
        }

        async showSuccesToast(message: string) {
          const toast = await this.toastCtrl.create({
            message: message,
            duration: 5000,
            position: 'bottom',
            showCloseButton: true
          });
          toast.present();
        }

        async showFailToast(appName: string) {
          const toast = await this.toastCtrl.create({
            message: `${appName} is not installed on your device`,
            duration: 5000,
            position: 'top'
          });
           toast.present();
        }

}

Great you may notice that we are using ToastController from ionic-angular, that's because sometimes it may happens that a specific social app may not be installed in user's device, so we need to inform him but with a good experience and friendly.

It's time to go the front page and add this social sharing functionalities, let's image that you have a page profile.ts and you want the user when he clicks on share an Action Sheet appears with all social social media that you want, here is the code for:

profile.html

<ion-content padding>

    <h2>Share this profile</h2>

    <div class="icon"><ion-icon [name]="icon"></ion-icon></div>

    <div class="container">

        <button ion-button
                (click)="presentActionSheet()"
                round
                medium
                text-capitalize
                color="blue">Yes I want to share this</button>
        <br>
        <button ion-button
                (click)="navigateBack()"
                clear
                small
                text-capitalize
                color="danger">Go back</button>

    </div>

profile.ts

import { Component } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  ActionSheetController
} from "ionic-angular";
import { SocialProvider } from "../../providers/social/social";
import { AdsProvider } from "../../providers/ads/ads";

@IonicPage()
@Component({
  selector: "page-opinion",
  templateUrl: "opinion.html"
})
export class OpinionPage {
  message: string;
  image: string;
  url: string;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public actionSheetCtrl: ActionSheetController,
    public _social: SocialProvider
  ) {}

  ionViewDidLoad() {
    this.url ="Url_you_want_to_share";
    this.image ="Link_to_an_image";
        this.message="a message goes here";
  }

  navigateBack() {
    this.navCtrl.pop();
  }

  presentActionSheet() {
    const actionSheet = this.actionSheetCtrl.create({
      buttons: [
        {
          text: "Share on Facebook",
          role: "destructive",
          cssClass: " action-facebook",
          icon: "logo-facebook",
          handler: () => {
            this._social.share(
              "com.facebook.katana",
              "Facebook",
              "facebook",
              this.message,
              this.subject,
              this.image,
              this.url
            );
          }
        },
        {
          text: "Share on Whatsup",
          role: "destructive",
          cssClass: " action-whatsup",
          icon: "logo-whatsapp",
          handler: () => {
            this._social.share(
              "com.whatsapp",
              "Whatsapp",
              "whatsapp",
              this.message,
              this.subject,
              this.image,
              this.url
            );
          }
        },
        {
          text: "Share on Instagram",
          role: "destructive",
          cssClass: " action-instagram",
          icon: "logo-instagram",
          handler: () => {
            this._social.share(
              "com.instagram.android",
              "Instagram",
              "instagram",
              this.message,
              this.subject,
              this.image,
              this.url
            );
          }
        },
        {
          text: "Share on Twitter",
          role: "destructive",
          cssClass: " action-twitter",
          icon: "logo-twitter",
          handler: () => {
            this._social.share(
              "com.twitter.android",
              "Twitter",
              "twitter",
              this.message,
              this.subject,
              this.image,
              this.url
            );
          }
        },
        {
          text: "Share on other Social medias",
          role: "destructive",
          cssClass: " action-regular",
          icon: "share",
          handler: () => {
            this._social.share(
              "none",
              "Share",
              "none",
              this.message,
              this.subject,
              this.image,
              this.url
            );
          }
        }
      ]
    });
    actionSheet.present();
  }
}

For now everything should be fine and the page should looks like that: Ionic Social Sharing Page

If you are wondering why those buttons looks styled, don't worry it's just some scss rules that I added in app.scss if you like that style you can copy it from here to that files and it should be just like that here is the scss code:

//social sharing buttons
button.action-facebook{
    background-color: #3B5998 !important;
    color: white!important;
}

button.action-twitter{
    background-color: #1DA1F2 !important;
    color: white!important;
}

button.action-instagram{
    color: white!important;
    background: #f09433;
    background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%) !important;
    background: -webkit-linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%) !important;
    background: linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%) !important;
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f09433', endColorstr='#bc1888',GradientType=1 ) !important;
}

button.action-whatsup{
    background-color: #128C7E !important;
    color: white!important;
}

button.action-regular{
    background-color: color($colors, dark) !important;
    color: white!important;
}

.action-sheet-group{
    padding: 0 !important;
}

Okay, I think that I'm done with social sharing functionality and I hop you like this tutorial and helps you, if you still want to know about ionic framework please check the specific tag for that, I recently added a tutorial about how to add Admob Free plugin to ionic project. thanks again and don't forget to improve this tutorial and share it with us.

Read also