简体   繁体   English

如何在离子应用程序中实现社交共享

[英]How to implement Social Sharing in ionic app

I am new in ionic-cordova and currently working on an app for a wordpress site. 我是ionic-cordova的新手,目前正在为wordpress网站开发应用程序。 I want to put a share button in my post details page so i can be able to share the post via apps installed in the android phone. 我想在我的帖子详细信息页面上放置一个分享按钮,这样我就可以通过安装在Android手机中的应用程序分享该帖子。

I have already installed the plugin as seen in my config.xml 我已经安装了config.xml中所示的插件

<plugin name="cordova-plugin-x-socialsharing" spec="^5.2.1" />

and in the app.module.ts file 并在app.module.ts文件中

 import { SocialSharing } from '@ionic-native/social-sharing';
.
.
.
providers: [
    StatusBar,
    SplashScreen,
    NativeStorage,
    WordpressService,
    AuthenticationService,
    SocialSharing

Here is my post.ts file code 这是我的post.ts文件代码

 import { Component } from '@angular/core';
    import { NavParams, NavController, AlertController } from 'ionic-angular';
    import { HomePage } from '../home/home';
    import { WordpressService } from '../../../services/wordpress.service';
    import { AuthenticationService } from '../../../services/authentication.service';
    import { Observable } from "rxjs/Observable";
    import 'rxjs/add/operator/map';
    import 'rxjs/add/observable/forkJoin';
    //library for social-sharing


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


    /**
     * Generated class for the PostPage page.
     *
     * See https://ionicframework.com/docs/components/#navigation for more info on
     * Ionic pages and navigation.
     */


    @Component({
      selector: 'page-post',
      templateUrl: 'post.html'
    })
    export class PostPage {

      post: any;
      user: string;
      comments: Array<any> = new Array<any>();
      categories: Array<any> = new Array<any>();
      morePagesAvailable: boolean = true;

      constructor(
        public navParams: NavParams,
        public navCtrl: NavController,
        public alertCtrl: AlertController,
        public wordpressService: WordpressService,
        public authenticationService: AuthenticationService,
        private socialSharing: SocialSharing
      ) {

      }

      ionViewWillEnter(){
        this.morePagesAvailable = true;

        this.post = this.navParams.get('item');

        Observable.forkJoin(
          this.getAuthorData(),
          this.getCategories(),
          this.getComments())
          .subscribe(data => {
            this.user = data[0].name;
            this.categories = data[1];
            this.comments = data[2];
          });
      }

      getAuthorData(){
        return this.wordpressService.getAuthor(this.post.author);
      }

      getCategories(){
        return this.wordpressService.getPostCategories(this.post);
      }

      getComments(){
        return this.wordpressService.getComments(this.post.id);
      }

      loadMoreComments(infiniteScroll) {
        let page = (this.comments.length/10) + 1;
        this.wordpressService.getComments(this.post.id, page)
        .subscribe(data => {
          for(let item of data){
            this.comments.push(item);
          }
          infiniteScroll.complete();
        }, err => {
          console.log(err);
          this.morePagesAvailable = false;
        })
      }

      goToCategoryPosts(categoryId, categoryTitle){
        this.navCtrl.push(HomePage, {
          id: categoryId,
          title: categoryTitle
        })
      }

//Social sharing implementation here

        shareItem() {
            let options = {
                                message: 'share this', // not supported on some apps (Facebook, Instagram)
                                subject: 'the subject', // fi. for email
                                files: ['', ''], // an array of filenames either locally or remotely
                                url: 'https://example.com/',
                                chooserTitle: 'Pick an app' // Android only, you can override the default share sheet title
                            }
                            SocialSharing.shareWithOptions(options).then((result) => {
                                console.log("Share completed? ", result.completed); // On Android apps mostly return false even while it's true
                                console.log("Shared to app: ", result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
                            }, (err) => {
                                console.log("Sharing failed with message: ", err);
                            });
        }
    }

Here is my post.html file code 这是我的post.html文件代码

 <button ion-button clear small color="danger" icon-left (click)="shareItem()">
           <ion-icon name='share-alt'></ion-icon>
           Share
         </button>

Your guidance will be much appreciated. 您的指导将不胜感激。

EDIT 编辑

below are the errors are getting 下面是错误越来越

WEBPACK_IMPORTED_MODULE_8__ionic_native_social_sharing .a.shareWithOptions is not a function WEBPACK_IMPORTED_MODULE_8__ionic_native_social_sharing .a.shareWithOptions不是函数

When i try to run command ionic cordova run android i get this error 当我尝试运行命令ionic cordova run android此错误

[21:24:30]  transpile started ...                                               
[21:24:44]  typescript: C:/Ionic/Final/src/pages/tabs/post/post.ts, line: 103   
            Property 'shareWithOptions' does not exist on type 'typeof SocialSha
ring'.                                                                          

     L103:  SocialSharing.shareWithOptions(options).then((result) => {          
     L104:      console.log("Share completed? ", result.completed); // On Androi
d apps mostly return false even while it's true                                 

Error: Failed to transpile program                                              
    at new BuildError (C:\Ionic\Final\node_modules\@ionic\app-scripts\dist\util\
errors.js:16:28)                                                                
    at C:\Ionic\Final\node_modules\@ionic\app-scripts\dist\transpile.js:159:20  
    at new Promise (<anonymous>)                                                
    at transpileWorker (C:\Ionic\Final\node_modules\@ionic\app-scripts\dist\tran
spile.js:107:12)                                                                
    at Object.transpile (C:\Ionic\Final\node_modules\@ionic\app-scripts\dist\tra
nspile.js:64:12)                                                                
    at C:\Ionic\Final\node_modules\@ionic\app-scripts\dist\build.js:109:82      
    at <anonymous>                                                              
[21:24:44]  copy finished in 14.75 s

In this line 在这条线

SocialSharing.shareWithOptions(options).then((result) => {
                                console.log("Share completed? ", result.completed); // On Android apps mostly return false even while it's true
                                console.log("Shared to app: ", result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
                            }, 

you need to use 你需要使用

this.socialSharing.share...

Hope this helps. 希望这可以帮助。

Remove all the shareItem function code from the post.ts file post.ts文件中删除所有shareItem功能代码

//Social sharing implementation here

        shareItem() {
            let options = {
                                message: 'share this', // not supported on some apps (Facebook, Instagram)
                                subject: 'the subject', // fi. for email
                                files: ['', ''], // an array of filenames either locally or remotely
                                url: 'https://example.com/',
                                chooserTitle: 'Pick an app' // Android only, you can override the default share sheet title
                            }
                            SocialSharing.shareWithOptions(options).then((result) => {
                                console.log("Share completed? ", result.completed); // On Android apps mostly return false even while it's true
                                console.log("Shared to app: ", result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
                            }, (err) => {
                                console.log("Sharing failed with message: ", err);
                            });
        }

replace the code in the post.html 替换post.html中的代码

<button ion-button clear small color="danger" icon-left (click)="shareItem()">
           <ion-icon name='share-alt'></ion-icon>
           Share
         </button>

With

<button ion-fab class="share" mini onclick="window.plugins.socialsharing.share('null', 'null', 'https://www.google.nl/images/srpr/logo4w.png', null)">Share</button>

using ion-fab makes the button look much better 使用ion-fab使按钮看起来更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM