Posting to Facebook from an app

I figured this might come in handy for others out there as it took me a while to sort out the various bugs (mostly because I skimmed the documentation).

What I wanted to achieve was the ability for a game player to post his/her score to their timeline. Although it took me a while to figure out it’s really not as hard as some other blogs/forums make out. First download the Facebook plugin from the Unity Asset Store and import it into your game.

One gotcha that didn’t seem to get mentioned was the necessity to include a “using System;”. This ensures the Uri identifier is recognized. The following code is all that is necessary (some may be specific to my app but I’m sure you’ll get the idea).

using System;
using UnityEngine;
using UnityEngine.UI;
using Facebook.Unity;

public class Facebook : MonoBehaviour {
    void Awake() {
        if (!FB.IsInitialized) {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        }
        else {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }
    }

    private void InitCallback() {
        if (FB.IsInitialized) {
            // Signal an app activation App Event
            FB.ActivateApp();
            // Continue with Facebook SDK
            // ...
        }
        else {
            Debug.Log("Failed to Initialize the Facebook SDK");
        }
    }

    private void OnHideUnity(bool isGameShown) {
        if (!isGameShown) {
            // Pause the game - we will need to hide
            Time.timeScale = 0;
        }
        else {
            // Resume the game - we're getting focus again
            Time.timeScale = 1;
        }
    }

    public void ButtonFacebook() {
        FB.ShareLink(
            contentURL: new Uri("PUT LINK TO THE PAGE/STORE PAGE YOU WISH TO LINK TO"),
            contentTitle: "TITLE",
            contentDescription: "DESCRIPTION",
            photoURL: new Uri("LINK TO A PICTURE"),
            callback: ShareCallback
        );
    }

    private void ShareCallback(IShareResult result) {
        if (result.Cancelled || !String.IsNullOrEmpty(result.Error)) {
            Debug.Log("ShareLink Error: " + result.Error);
        }
        else if (!String.IsNullOrEmpty(result.PostId)) {
            // Print post identifier of the shared content
            Debug.Log(result.PostId);
        }
        else {
            // Share succeeded without postID
            Debug.Log("ShareLink success!");
        }
    }
}

After that create a button in your scene and point it to ButtonFaceBook() method.

Hope that helps someone.
Cheers, J

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.