Wednesday, 14 March 2018

Implementing Social Sharing in Ionic 2 and ionic 3.

Social Sharing in ionic is used to Share Text, Files, Images, and Links via Social Networks, SMS, and Email. In ionic, Social Sharing can be achieved by Ionic Native. Ionic Native allows to add native functionality to ionic application via plugins.
In this Post we are going to look at, how to integrate social sharing functionality in an ionic application.
This post assumes that you already have the ionic project created and running.

Create a socialsharing page.

Execute below command in your projects command prompt to add socialsharing page to your project "pages" folder in "src" directory.

ionic generate page socialsharing

this will generate socialsharing folder in your project's src/pages folder.
Note : import the socialsharing page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "socialsharing.module.ts" file in your new page file (ie in socialsharing folder). the "app.module.ts" should look something like this after socialsharing page is imported.

Modify app.module.ts file

app.module.ts



        import { BrowserModule } from '@angular/platform-browser';
        import { ErrorHandler, NgModule } from '@angular/core';
        import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

        import { MyApp } from './app.component';
        import { HomePage } from '../pages/home/home';
        import { ListPage } from '../pages/list/list';
        import { SocialsharingPage } from '../pages/socialsharing/socialsharing';

        import { StatusBar } from '@ionic-native/status-bar';
        import { SplashScreen } from '@ionic-native/splash-screen';

        @NgModule({
        declarations: [
            MyApp,
            HomePage,
            ListPage,
            SocialsharingPage
        ],
        imports: [
            BrowserModule,
            IonicModule.forRoot(MyApp)

        ],
        bootstrap: [IonicApp],
        entryComponents: [
            MyApp,
            HomePage,
            ListPage,
            SocialsharingPage
        ],
        providers: [
            StatusBar,
            SplashScreen,
            {provide: ErrorHandler, useClass: IonicErrorHandler},

        ]
        })
        export class AppModule {}



That is all for the app.module file your app should run fine now.

Install the Social Sharing plugin.


Execute below commands in your projects command prompt to install ionic Social Sharing plugin to your project.

ionic cordova plugin add cordova-plugin-x-socialsharing

npm install --save @ionic-native/social-sharing
Now, import it in your component, and also inject into your components constructor.
Copy and paste the below give code to the socialsharing.ts file imports.

   
   import { SocialSharing } from '@ionic-native/social-sharing';
   
   constructor( ..., private socialSharing: SocialSharing) { ... }
   

Next, for the share functionality. if you want to open a sheet with all the social media options, use the below share function .

  this.socialSharing.share('Message', 'Subject', 'http://www.ionicsync.com/images/logo.png', 'http://www.ionicsync.com').then(() => {

     console.log('Shared Successfully');

  }).catch(() => {

     console.log('Sharing Failed');

  });

Sharing via some applications is not support due to some reasons , for that we should first check if it is supported. Below function checks if sharing via email is supported.


  this.socialSharing.canShareViaEmail().then(() => {
    console.log('Sharing via email is possible');
    this.socialSharing.shareViaEmail('Body', 'Subject', ['recipient@example.org']).then(() => {
       console.log('Success!');
     }).catch(() => {
       console.log('Error!');
     });
  }).catch(() => {
    console.log('Sharing via email is not possible');
  });


This can be done with all the social applications the plugin supports. We also have shareWithOptions().


  shareViaOptions(){
       var options = {
        message: 'share via',
        subject: 'Please select any social media to share.',
        url: 'http://www.ionicsync.com',
        chooserTitle: 'SHARE' // Android only, you can override the default share sheet title
      }


      this.socialSharing.shareWithOptions(options).then((res) => {
       console.log('Success!');
      }).catch(() => {
       console.log('Error!');
      });
      
  }

Your socialsharing.ts file should look something like this.

socialsharing.ts


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

   constructor( ..., private socialSharing: SocialSharing) { ... }

   @IonicPage()
   @Component({
    selector: 'page-socialsharing',
    templateUrl: 'socialsharing.html',
   })
   export class SocialSharing {
     ionViewDidLoad() {
           console.log('ionViewDidLoad SharePage');
     }  

     share(){
            this.socialSharing.share('Message', 'Subject', 'http://www.ionicsync.com/images/logo.png', 'http://www.ionicsync.com').then(() => {

                console.log('Shared Successfully');

            }).catch(() => {

                console.log('Sharing Failed');

            });
    };

    checkShare(){
        this.socialSharing.canShareViaEmail().then(() => {
                console.log('Sharing via email is possible');
                this.socialSharing.shareViaEmail('Body', 'Subject', ['recipient@example.org']).then(() => {
                console.log('Success!');
                }).catch(() => {
                console.log('Error!');
                });
            }).catch(() => {
                console.log('Sharing via email is not possible');
            });
    } ;  

   shareViaOptions(){
      var options = {
        message: 'share via',
        subject: 'Please select any social media to share.',
        url: 'http://www.ionicsync.com',
        chooserTitle: 'SHARE' // Android only, you can override the default share sheet title
      }


      this.socialSharing.shareWithOptions(options).then((res) => {
       console.log('Success!');
      }).catch(() => {
       console.log('Error!');
      });
      
    };
   
   }


One more thing is, you should also import the "SocialSharing" to your apps app.module.ts file, otherwise you will get a provider issue. That's it if you have any queries, please leave a comment below.

1 comment: