androidfacebookunity-game-enginefacebook-sdk-3.0facebook-unity-sdk

Upload picture to facebook from unity


Im working on a unity game where you can take a picture and upload this picture to facebook from unity along with some tags and stuff (much like friendsmash). The problem is that i do not have a web-server that i can put the screenshots on, and the Fb.Feeb(picture:) attribute only accepts urls.

I have read that you can use HTTP POST to post the picture to the users images and then use that link in picture:, but i dont know anything about HTTP POST and i couldnt figure out how to do it.

I have also read that you can use FB.API() to somehow do this, but i couldnt figure it out.

Any sample code would be greatly appreciated.

My current code:

private string _path = "file://" + System.IO.Path.Combine(Application.persistentDataPath, "Images/image.png");

void Start ()
    {
        if (!FB.IsLoggedIn)
            FB.Login("email, publish_actions, publish_stream, user_photos", LoginCallback);
        StartCamera();
    }


private void OnBragClicked()

{
    FbDebug.Log("OnBragClicked");

//Post(); <-- dont know how

FB.Feed(
    linkCaption: "#hashtag",
    picture: "???",
    linkName: "Im hashtaging!",
    link: "https://apps.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ?  FB.UserId : "guest")
    );
}


 void TakeSnapshot()

{
    _snap = new Texture2D(_webCamTexture.width, _webCamTexture.height);
    _snap.SetPixels(_webCamTexture.GetPixels());
    _snap.Apply();

//System.IO.File.WriteAllBytes(_path, _snap.EncodeToPNG());
}

Solution

  • The facebook sdk does have a way to make this happen after all. You need to use Fb.API(). This is the way it worked for me:

    private void TakeScreenshot()
    {
        var snap = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        snap.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        snap.Apply();
        var screenshot = snap.EncodeToPNG();
    
        var wwwForm = new WWWForm();
        wwwForm.AddBinaryData("image", screenshot, "barcrawling.png");
    
        FB.API("me/photos", HttpMethod.POST, LogCallback, wwwForm);
    }
    

    In general terms, to add some sort of caption, it's along the lines...

    private byte[] postcardAsBytes;
    string textMessage = "Play this great game at http://blah.com.";
    Dictionary<string, object> d = new Dictionary<string, object>
      {
      { "message", textMessage },
      { "picture", postcardAsBytes }
      };
    Facebook.instance.graphRequest(
            "me/photos", HTTPVerb.POST, d, yourCompletionHandler);
    // in this example using the prime31 plugin, rather than the fb sdk
    

    The key field seems to be "message". Confusingly, the "dictionary" field documented by FB, seems to just not work, so try "message" at first.