如何使用Xamarin Forms在Facebook上分享帖子

时间:2016-10-28 08:04:37

标签: facebook-graph-api xamarin.ios xamarin.android xamarin.forms

我目前正在使用Xamarin,我对xamarin表单中的facebook共享选项感到困惑,特别是在Xamarin Android中,IOS代码是

public void ShareOnFacebook(IFacebookDelegate pDele)         {

        string[] perm = {"publish_actions"};
        if (AccessToken.CurrentAccessToken == null || !AccessToken.CurrentAccessToken.HasGranted("publish_actions"))
        {
            UIViewController mainController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            _manager.LogInWithPublishPermissions(perm, mainController, (result, error) =>
            {
                if (error != null || result.IsCancelled)
                {
                }
                else {
                    ShareNow();
                }
            });
        } else {
            ShareNow();
        }

    }

唯一阻止我的是Xamarin Android facebook发布分享。 任何人都可以根据Xamarin Android修改此代码或分享他/她自己的代码。

1 个答案:

答案 0 :(得分:1)

我已经为twitter和fb实现了分享。

iOS版

您可以使用ios的本地社交服务进行共享,如果没有可用的话 OAuth2Authenticator获取访问令牌,然后使用FB graph

发布
public void ShareViaSocial(string serviceType, string urlToShare)
        {
            socialKind = serviceType == "Twitter" ? SLServiceKind.Twitter : SLServiceKind.Facebook;

            if (SLComposeViewController.IsAvailable(socialKind))
            {
                _socialComposer = serviceType == "Twitter" ? SLComposeViewController.FromService(SLServiceType.Twitter) : SLComposeViewController.FromService(SLServiceType.Facebook);
                _socialComposer.AddUrl(new Uri(urlToShare));

                viewController.PresentViewController(_socialComposer, true, () =>
                {
                    _socialComposer.CompletionHandler += (result) =>
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            viewController.DismissViewController(true, null);

                            if (result == SLComposeViewControllerResult.Done)
                            { OnShare(this, ShareStatus.Successful); }
                            else
                            { OnShare(this, ShareStatus.NotSuccessful); }
                        });
                    };

                });
            }

            //If user doest have fb app and no credential for social services we use fb graph
            else if (socialKind == SLServiceKind.Facebook)
            {
                var auth = new OAuth2Authenticator(
                clientId: SharedConstants.FacebookLiveClientId,
                scope: SharedConstants.FacebookScopes,
                authorizeUrl: new Uri(SharedConstants.FacebookAuthorizeUrl),
                redirectUrl: new Uri(SharedConstants.FacebookRedirectUrl));
                viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
                auth.AllowCancel = true;
                auth.Completed += (s, e) =>
                {
                    //hide the webpage after completed login
                    viewController.DismissViewController(true, null);
                    // We presented the UI, so it's up to us to dimiss it on iOS.


                    if (e.IsAuthenticated)
                    {
                        Account fbAccount = e.Account;
                        Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
                        var requestUrl = new Uri("https://graph.facebook.com/me/feed");
                        var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);

                        request.GetResponseAsync().ContinueWith(this.requestResult);
                    }
                    else { OnShare(this, ShareStatus.NotSuccessful); }
                };
                auth.Error += Auth_Error;
            }
            //If user doest have twitter app and no credential for social services we use xanarub auth for token and call twitter api for sending tweets

            else
            {
                var auth = new OAuth1Authenticator(
                               SharedConstants.TwitterConsumerKey,
                               SharedConstants.TwitterConsumerSecret,
                               new Uri(SharedConstants.TwitterRequestUrl),
                               new Uri(SharedConstants.TwitterAuth),
                               new Uri(SharedConstants.TwitterAccessToken),
                               new Uri(SharedConstants.TwitterCallBackUrl));

                auth.AllowCancel = true;
                // auth.ShowUIErrors = false;
                // If authorization succeeds or is canceled, .Completed will be fired.
                auth.Completed += (s, e) =>
                {
                    // We presented the UI, so it's up to us to dismiss it.
                    viewController.DismissViewController(true, null);

                    if (e.IsAuthenticated)
                    {
                        Account twitterAccount = e.Account;
                        Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
                        var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
                        //for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
                        request.GetResponseAsync().ContinueWith(this.requestResult);
                    }
                    else { OnShare(this, ShareStatus.NotSuccessful); }
                };
                auth.Error += Auth_Error;
                //auth.IsUsingNativeUI = true;
                viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
            }
        }

Android版

您可以使用原生facebook ShareDialog,如果不可用,请使用OAuth2Authenticator获取访问令牌,然后使用FB graph发布 并使用OAuth1Authenticator在twitter上摆姿势

public void ShareViaSocial(string serviceType, string urlToShare)
        {
            ShareDialog di = new ShareDialog(MainActivity.Instance);
             var facebookShareContent = new ShareLinkContent.Builder();
             facebookShareContent.SetContentUrl(Android.Net.Uri.Parse(urlToShare));
            if (serviceType == "Facebook")
            {
                if (di.CanShow(facebookShareContent.Build(), ShareDialog.Mode.Automatic))
                {
                    di.Show(facebookShareContent.Build());
                }
                else
                {
                    var auth = new OAuth2Authenticator(
                    clientId: 'ClientId',
                    scope: "public_profile,publish_actions",
                    authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                    redirectUrl: new Uri( "http://www.facebook.com/connect/login_success.html"));

                    MainActivity.Instance.StartActivity(auth.GetUI(MainActivity.Instance.ApplicationContext));

                    auth.AllowCancel = true;
                    auth.Completed += (s, e) =>
                    {
                        if (e.IsAuthenticated)
                        {
                            Account fbAccount = e.Account;
                            Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
                            var requestUrl = new Uri("https://graph.facebook.com/me/feed");
                            var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);

                            request.GetResponseAsync().ContinueWith(this.requestResult);
                        }
                        else { OnShare(this, ShareStatus.NotSuccessful); }
                    };
                    auth.Error += Auth_Error;
                }
            }

            else
            {
                var auth = new OAuth1Authenticator(
                               'TwitterConsumerKey',
                               'TwitterConsumerSecret',
                               new Uri("https://api.twitter.com/oauth/request_token"),
                               new Uri("https://api.twitter.com/oauth/authorize"),
                               new Uri("https://api.twitter.com/oauth/access_token"),
                               new Uri('TwitterCallBackUrl'));

                auth.AllowCancel = true;
                // auth.ShowUIErrors = false;
                // If authorization succeeds or is canceled, .Completed will be fired.
                auth.Completed += (s, e) =>
                {
                    // We presented the UI, so it's up to us to dismiss it.

                    if (e.IsAuthenticated)
                    {
                        Account twitterAccount = e.Account;
                        Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
                        var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
                        //for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
                        request.GetResponseAsync().ContinueWith(this.requestResult);
                    }
                    else { OnShare(this, ShareStatus.NotSuccessful); }
                };
                auth.Error += Auth_Error;
                //auth.IsUsingNativeUI = true;
                MainActivity.Instance.StartActivity(auth.GetUI(MainActivity.Instance.ApplicationContext));
            }


        }