コード例 #1
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Initialize the SDK before executing any other operations
            FacebookSdk.SdkInitialize(Application.Context);

            // create callback manager using CallbackManagerFactory
            callbackManager = CallbackManagerFactory.Create();

            LoginManager.Instance.RegisterCallback(callbackManager, new MyFacebookCallback <LoginResult>(this));

            shareDialog   = new ShareDialog(this);
            shareCallback = new MySharedDialogCallback <SharerResult>(this);
            shareDialog.RegisterCallback(callbackManager, shareCallback);

            if (savedInstanceState != null)
            {
                var name = savedInstanceState.GetString(PENDING_ACTION_BUNDLE_KEY);
                System.Enum.TryParse(name, true, out pendingAction);
            }

            SetContentView(Resource.Layout.main);

            profileTracker = new MyProfileTracker(this);

            profilePictureView = FindViewById <ProfilePictureView>(Resource.Id.profilePicture);
            greeting           = FindViewById <TextView>(Resource.Id.greeting);

            postStatusUpdateButton        = FindViewById <Button>(Resource.Id.postStatusUpdateButton);
            postStatusUpdateButton.Click += (sender, args) =>
            {
                OnClickPostStatusUpdate();
            };

            postPhotoButton        = FindViewById <Button>(Resource.Id.postPhotoButton);
            postPhotoButton.Click += (sender, args) =>
            {
                OnClickPostPhoto();
            };

            // Can we present the share dialog for regular links?
            canPresentShareDialog = ShareDialog.CanShow(Class.FromType(typeof(ShareLinkContent)));

            // Can we present the share dialog for photos?
            canPresentShareDialogWithPhotos = ShareDialog.CanShow(Class.FromType(typeof(SharePhotoContent)));
        }
コード例 #2
0
        public async void ShareFacebookChallenge(object source, ChallengeModel model, string message = null)
        {
            ShareTemplateModel shareTemplate = null;
            ShareResponseModel shareResponse = null;
            await SL.Manager.RefreshShareTemplate(model.ShareTemplateURL, (response) =>
            {
                shareTemplate = response?.ShareTemplate;
                shareResponse = response;
            });

            NSUrl url = new NSUrl(shareTemplate?.PostHref ?? model.ShareImage);

            ShareDialog dialog = new ShareDialog();

            dialog.SetShouldFailOnDataError(true);
            dialog.FromViewController = source as UIViewController;
            dialog.SetDelegate(source as ISharingDelegate ?? new FBSharingDelegate());

            if (string.IsNullOrEmpty(message) && model.FBShareType == "image")
            {
                UIImageView imageView = new UIImageView();
                try
                {
                    await ImageService.Instance.LoadUrl(model.ShareImage).IntoAsync(imageView);
                }
                catch (Exception)
                {
                    try
                    {
                        await ImageService.Instance.LoadUrl(model.Image).IntoAsync(imageView);
                    }
                    catch (Exception)
                    {
                    }
                }

                dialog.SetShareContent(new SharePhotoContent()
                {
                    Photos = new SharePhoto[] { SharePhoto.From(imageView.Image, true) }
                });
                dialog.Mode = ShareDialogMode.Native;
            }
            else if (string.IsNullOrEmpty(message) && (model.FBShareType == "link" || model.FBShareType == null))
            {
                ShareLinkContent contentLink = new ShareLinkContent();
                if (string.IsNullOrEmpty(url?.AbsoluteString))
                {
                    new UIAlertView("Sharing Error", string.IsNullOrEmpty(shareResponse?.ResponseMessage) ? "Sorry. No url come from server" : shareResponse.ResponseMessage, source as IUIAlertViewDelegate, "Ok").Show();
                    return;
                }
                contentLink.SetContentUrl(url);

                dialog.SetShareContent(contentLink);
                dialog.Mode = ShareDialogMode.Web;
            }
            else
            {
                SendOpenGraph(source, model, message);
                return;
            }

            if (!dialog.CanShow())
            {
                SendOpenGraph(source, model, message);
                return;
            }
            dialog.Show();

            if (dialog.Mode == ShareDialogMode.Web)
            {
                StylishFbWebDialog();
            }
        }
コード例 #3
0
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            string title          = Intent.GetStringExtra("Title");
            string description    = Intent.GetStringExtra("Description");
            string imageUrl       = Intent.GetStringExtra("ImageUrl");
            string localImagePath = Intent.GetStringExtra("ImagePath");
            string localVideoPath = Intent.GetStringExtra("VideoPath");
            string link           = Intent.GetStringExtra("Link");

            base.OnCreate(savedInstanceState);

            FacebookSdk.ApplicationId   = Droid.DS.FacebookLogin.FacebookAppId;
            FacebookSdk.ApplicationName = "";
            FacebookSdk.SdkInitialize(ApplicationContext);


            callbackManager = CallbackManagerFactory.Create();
            fbShareCallback = new FacebookCallback <SharerResult>
            {
                HandleSuccess = loginResult =>
                {
                    Toast.MakeText(ApplicationContext, "Your post has been shared successfully.", ToastLength.Long).Show();
                    ShareCompleted(ShareStatus.Success, "Your post has been shared successfully.");
                },
                HandleCancel = () =>
                {
                    Toast.MakeText(ApplicationContext, "Cancelled", ToastLength.Long).Show();
                    ShareCompleted(ShareStatus.Cancelled, "User has cancelled.");
                },
                HandleError = loginError =>
                {
                    Toast.MakeText(ApplicationContext, "Error " + loginError.Message, ToastLength.Long).Show();
                    ShareCompleted(ShareStatus.Error, loginError.Message);
                }
            };
            ShareContent shareContent = null;

            if (!string.IsNullOrWhiteSpace(localImagePath))
            {
                SharePhoto sharePhoto = (SharePhoto) new SharePhoto.Builder()
                                        .SetBitmap(Android.Graphics.BitmapFactory.DecodeFile(localImagePath))
                                        .SetCaption(title)
                                        .Build();
                SharePhotoContent content = new SharePhotoContent.Builder()
                                            .AddPhoto(sharePhoto)
                                            .Build();

                shareContent = content; // new ShareMediaContent.Builder().AddMedium(sharePhoto).Build();
            }

            else if (!string.IsNullOrWhiteSpace(localVideoPath))
            {
                Android.Net.Uri videoFileUri = Android.Net.Uri.FromFile(new Java.IO.File(localVideoPath));
                ShareVideo      shareVideo   = (ShareVideo) new ShareVideo.Builder()
                                               .SetLocalUrl(videoFileUri)
                                               .Build();
                ShareVideoContent content = new ShareVideoContent.Builder()
                                            .SetVideo(shareVideo)
                                            .Build();
                shareContent = content;
            }
            else
            {
                var contentBuilder = new ShareLinkContent.Builder();
                contentBuilder.SetContentTitle(title);
                if (!string.IsNullOrWhiteSpace(description))
                {
                    contentBuilder.SetContentDescription(description);
                }
                if (!string.IsNullOrWhiteSpace(imageUrl))
                {
                    contentBuilder.SetImageUrl(Android.Net.Uri.Parse(imageUrl));
                }
                if (!string.IsNullOrWhiteSpace(link))
                {
                    contentBuilder.SetContentUrl(Android.Net.Uri.Parse(link));
                }
                shareContent = contentBuilder.Build();
            }
            if (ShareDialog.CanShow(shareContent.Class))
            {
                var shareDialog = new ShareDialog(this);
                shareDialog.RegisterCallback(callbackManager, fbShareCallback);
                shareDialog.Show(shareContent, ShareDialog.Mode.Automatic);
                return;
            }
            else
            {
                var FBLoginCallback = new FacebookCallback <LoginResult>
                {
                    HandleSuccess = loginResult =>
                    {
                        ShareApi.Share(shareContent, fbShareCallback);
                    },
                    HandleCancel = () =>
                    {
                        Toast.MakeText(ApplicationContext, "Cancelled", ToastLength.Long).Show();
                        ShareCompleted(ShareStatus.Cancelled, "User has cancelled.");
                    },
                    HandleError = loginError =>
                    {
                        LoginManager.Instance.LogOut();
                        Toast.MakeText(ApplicationContext, "Error " + loginError.Message, ToastLength.Long).Show();
                        ShareCompleted(ShareStatus.Error, loginError.Message);
                    }
                };
                LoginManager.Instance.RegisterCallback(callbackManager, FBLoginCallback);
                LoginManager.Instance.LogInWithPublishPermissions(this, new System.Collections.Generic.List <string>()
                {
                    "publish_actions"
                });
            }
        }
コード例 #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            FacebookSdk.SdkInitialize(this.ApplicationContext);

            callbackManager = CallbackManagerFactory.Create();

            var loginCallback = new FacebookCallback <LoginResult> {
                HandleSuccess = loginResult => {
                    HandlePendingAction();
                    UpdateUI();
                },
                HandleCancel = () => {
                    if (pendingAction != PendingAction.NONE)
                    {
                        ShowAlert(
                            GetString(Resource.String.cancelled),
                            GetString(Resource.String.permission_not_granted));
                        pendingAction = PendingAction.NONE;
                    }
                    UpdateUI();
                },
                HandleError = loginError => {
                    if (pendingAction != PendingAction.NONE &&
                        loginError is FacebookAuthorizationException)
                    {
                        ShowAlert(
                            GetString(Resource.String.cancelled),
                            GetString(Resource.String.permission_not_granted));
                        pendingAction = PendingAction.NONE;
                    }
                    UpdateUI();
                }
            };

            LoginManager.Instance.RegisterCallback(callbackManager, loginCallback);

            shareCallback = new FacebookCallback <SharerResult> {
                HandleSuccess = shareResult => {
                    Console.WriteLine("HelloFacebook: Success!");

                    if (shareResult.PostId != null)
                    {
                        var title    = Parent.GetString(Resource.String.error);
                        var id       = shareResult.PostId;
                        var alertMsg = Parent.GetString(Resource.String.successfully_posted_post, id);

                        ShowAlert(title, alertMsg);
                    }
                },
                HandleCancel = () => {
                    Console.WriteLine("HelloFacebook: Canceled");
                },
                HandleError = shareError => {
                    Console.WriteLine("HelloFacebook: Error: {0}", shareError);

                    var title    = Parent.GetString(Resource.String.error);
                    var alertMsg = shareError.Message;

                    ShowAlert(title, alertMsg);
                }
            };

            shareDialog = new ShareDialog(this);
            shareDialog.RegisterCallback(callbackManager, shareCallback);

            if (savedInstanceState != null)
            {
                var name = savedInstanceState.GetString(PENDING_ACTION_BUNDLE_KEY);
                pendingAction = (PendingAction)Enum.Parse(typeof(PendingAction), name);
            }

            SetContentView(Resource.Layout.main);

            profileTracker = new CustomProfileTracker {
                HandleCurrentProfileChanged = (oldProfile, currentProfile) => {
                    UpdateUI();
                    HandlePendingAction();
                }
            };

            profilePictureView = FindViewById <ProfilePictureView> (Resource.Id.profilePicture);

            greeting = FindViewById <TextView> (Resource.Id.greeting);

            postStatusUpdateButton        = FindViewById <Button> (Resource.Id.postStatusUpdateButton);
            postStatusUpdateButton.Click += (sender, e) => {
                PerformPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
            };

            postPhotoButton        = FindViewById <Button> (Resource.Id.postPhotoButton);
            postPhotoButton.Click += (sender, e) => {
                PerformPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
            };

            // Can we present the share dialog for regular links?
            canPresentShareDialog = ShareDialog.CanShow(Java.Lang.Class.FromType(typeof(ShareLinkContent)));

            // Can we present the share dialog for photos?
            canPresentShareDialogWithPhotos = ShareDialog.CanShow(Java.Lang.Class.FromType(typeof(SharePhotoContent)));
        }
コード例 #5
0
        public async Task ShareFacebookChallenge(object source, ChallengeModel model, string message = null, byte[] data = null, Action <ChallengesFacebookShareResponseType> viewModelResponse = null)
        {
            OpenGraphWasTry   = false;
            ViewModelResponse = viewModelResponse;
            Activity          = source as Activity;
            Model             = model;
            ShareTemplateModel shareTemplate = null;
            ShareResponseModel shareResponse = null;
            await SL.Manager.RefreshShareTemplate(Model.ShareTemplateURL, (response) =>
            {
                shareTemplate = response?.ShareTemplate;
                shareResponse = response;
            });

            try
            {
                ShareDialog dialog = new ShareDialog(Activity);
                dialog.RegisterCallback((Activity as MainActivity).CallBackManager, this);
                if (string.IsNullOrEmpty(message) && Model.FBShareType == "image")
                {
                    if (data == null && !string.IsNullOrEmpty(Model.Image))
                    {
                        data = await ImageUrlToByteArrayLocalConverter.ReadImageUrlToBytesArray(Model.Image);
                    }
                    if (data == null)
                    {
                        return;
                    }
                    var bitmapImage = await BitmapFactory.DecodeByteArrayAsync(data, 0, data.Length);

                    var photoBuilder = new SharePhoto.Builder();
                    photoBuilder.SetUserGenerated(true);
                    var sharePhoto            = photoBuilder.SetBitmap(bitmapImage);
                    SharePhotoContent content = new SharePhotoContent.Builder().AddPhoto(sharePhoto.Build()).Build();
                    if (dialog.CanShow(content, ShareDialog.Mode.Web))
                    {
                        dialog.Show(content, ShareDialog.Mode.Web);
                        return;
                    }
                }
                if (string.IsNullOrEmpty(message) && (Model.FBShareType == null || Model.FBShareType == "link"))
                {
                    var uri = Android.Net.Uri.Parse(shareTemplate?.PostHref ?? Model.ShareImage);

                    var linkBuilder = new ShareLinkContent.Builder();
                    linkBuilder.SetContentUrl(Android.Net.Uri.Parse(shareTemplate?.PostHref ?? Model.ShareImage));
                    ShareLinkContent content = linkBuilder.Build();

                    if (dialog.CanShow(content, ShareDialog.Mode.Web))
                    {
                        dialog.Show(content, ShareDialog.Mode.Web);
                        return;
                    }
                }

                ViewModelResponse(ChallengesFacebookShareResponseType.NativeUninstallApp);
            }
            catch (System.Exception ex)
            {
                await SendOpenGraph(Activity, Model, message, null, null, shareTemplate, shareResponse);
            }
            return;
        }