FB.API
Makes a call to the Graph API to get data, or take action on a user's behalf. This will almost always be used once a user is logged in, and an access token has been granted; the permissions encoded by the access token determine which Graph API calls will be available.
Parameters
There are two signatures for FB.API, one for passing a collection of argurments and another for passing more complicated data, like images.
public static void API(
string query
HttpMethod method,
FacebookDelegate<IGraphResult> callback = null,
IDictionary<string, string> formData = null
)
public static void API(
string query
HttpMethod method,
FacebookDelegate<IGraphResult> callback,
WWWForm formData
)
| Name | Type | Description | Default |
|---|---|---|---|
|
| The Graph API endpoint to call. e.g. | none |
|
| The HTTP method to use in the call, one of |
|
|
| A delegate which will receive the result of the call | none |
|
| The key/value pairs to be passed to the endpoint as arguments. | none |
Examples
Publish a user's score in your game (requires the publish_actions permission):
int score = 10000;
var scoreData =
new Dictionary<string, string>() {{"score", score.ToString()}};
FB.API ("/me/scores", HttpMethod.POST, APICallback, scoreData);
Take and publish a screenshot (requires publish_actions), requires version 4.3.3 or later:
private IEnumerator TakeScreenshot()
{
yield return new WaitForEndOfFrame();
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
byte[] screenshot = tex.EncodeToPNG();
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "Screenshot.png");
FB.API("me/photos", Facebook.HttpMethod.POST, APICallback, wwwForm);
}
Best Practices
Many kinds of data available via the Graph API do not change often. For example, users change their profile pictures infrequently, and their friend lists will often be the same between visits to your app. To reduce network I/O and improve your performance, consider reading these items on your server rather than your client, caching the results and then subscribing to realtime updates on those objects so you'll know when to refresh your cached versions.
Be sure to check the value passed into the callback, as it may reflect an error, rather than your desired query output. The most common cause of errors is an authorization problem, such as insufficient privileges or an expired access token; authorization errors look like this:
{
"code":400,
"body": {
"error": {
"message": "An active access token must be used to query information about the current user.",
"type": "OAuthException",
"code": 2500
}
}
}
See also our guide to using JSON with Unity.