Getting Text from IResult Facebook SDK, 7.2.0 - facebook

I am trying to get the player's username and then display it.
Recently, there was a breaking changes; IResult replacement for FBResult.
I was able to return a texture from the IGraphResult instead of FBResult, to display the profile picture, so I expect that the Text would be available as well but no.
So my issue is, where can I return the Text from?
Do I have to add anything to the IGraphResult?
Here is the code,
void DealWithUserName(FBResult result)
{
if(result.Error != null)
{
Debug.Log ("Problems with getting profile picture");
FB.API ("/me?fields=id,first_name", HttpMethod.GET, DealWithUserName);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
Text UserMsg = UIFBUsername.GetComponent<Text>();
UserMsg.text = "Hello, " + profile["first_name"];
}
Edited:
Okay, I did it.
It seems that I can also get the username from the IGraphResult.
So, I changed the FBResult to IGraphResult.
I changed result.Text to result.RawResult.
Here is the code, for anyone who needs it.
void DealWithUserName(IGraphResult result)
{
if(result.Error != null)
{
Debug.Log ("Problems with getting profile picture");
FB.API ("/me?fields=id,first_name", HttpMethod.GET, DealWithUserName);
return;
}
profile = Util.DeserializeJSONProfile(result.RawResult);
Text UserMsg = UIFBUsername.GetComponent<Text>();
UserMsg.text = "Hello, " + profile["first_name"];
}

Let's try it
private void DealWithUserName(IGraphResult result){
if (result.ResultDictionary != null) {
foreach (string key in result.ResultDictionary.Keys) {
Debug.Log(key + " : " + result.ResultDictionary[key].ToString());
// first_name : Chris
// id : 12345678901234567
}
}
Text UserName = UIUserName.GetComponent<Text>();
UserName.text = "Hello, "+ result.ResultDictionary["name"].ToString();
}

Related

Is it possible to show whatever is printed in the Debug.Log into the scene using a text?

I'm trying to convert the messages that appear in the unity console, in text inside the scene.
Do you have suggestions how to do it ?
Yes, in Debug.Log() you are already giving it a value or text to be shown in the console, so you can take that value and display it in a text object.
This code work in part, because now it shows me text that appear in console, but get only the first text, and then the other sentences are queued to be shown but this never happens because only the first sentence is shown.
enter code here
void OnEnable()
{
Application.logMessageReceivedThreaded += HandleLog;
}
void OnDisable()
{
Application.logMessageReceivedThreaded -= HandleLog;
}
void HandleLog(string logString, string stackTrace, LogType type)
{
if (type == LogType.Log){
string[] splitString = logString.Split(char.Parse(":"));
string debugKey = splitString[0];
string debugValue = splitString.Length > 1 ? splitString[1] :"";
if (debugLogs.ContainsKey(debugKey))
debugLogs[debugKey] = debugValue;
else
debugLogs.Add(debugKey, debugValue);
}
string displayText = "";
foreach ( KeyValuePair<string, string> log in debugLogs)
{
if(log.Value ==""){
displayText += log.Key + "\n ";
}
else{
displayText += log.Key + ": " + log.Value + "\n";
}
}
display.text = displayText;
}

How to attach multiple videos and photos to a status post with Facebook graph API

I'm trying to publish a post with multiple attached videos and photos via the Facebook Graph API. I uploaded the videos and photos first using a batch request and get the ids successfully for the uploaded media. Then I pass the media ids along with the post data using attached_media. Things work fine for single or multiple photos. But not for a single video or multiple videos. I got this error: "Graph returned an error: (#10) Application does not have permission for this action" whenever ids of videos are included in attached_media.
I know as a user you have the ability to attach multiple videos and photos to a Facebook post. Does the Facebook Graph API just flat out not support this for multiple videos?
I am working with C# and Unity
Here is the function that uploads videos and then sends a post with attached result videos ids:
private IEnumerator UploadMediaWithStatus(string message, string[] mediaUrls)
{
FacebookPostStatusUpdatedEvent.Invoke("Submitting FB post ... ");
var curPage = m_UserPages[FacebookFeedsList.GetInstance().ActiveFeed] as IDictionary<string, object>;
var fbClient = new FacebookClient(curPage["access_token"].ToString());
List<string> mediaIDs = new List<string> ();
foreach (string mediaUrl in mediaUrls)
{
WWW _media = new WWW("file://" + mediaUrl);
yield return _media;
if (!System.String.IsNullOrEmpty(_media.error))
{
FacebookPostStatusUpdatedEvent.Invoke("FB post failed: error loading media " + mediaUrl);
//TruLogger.LogError("cant load Image : " + _image.error);
yield break;
}
byte[] mediaData = null;
FacebookMediaObject medObj = new FacebookMediaObject();
JsonObject p = new JsonObject();
mediaData = _media.bytes;
medObj.SetValue(mediaData);
medObj.FileName = "InteractiveConsole.mp4";
medObj.ContentType = "multipart/form-data";
p.Add("description", message);
p.Add("source", medObj);
uploadedImgID = "";
fbClient.PostCompleted += OnPostImageUploadComplete;
fbClient.PostAsync("/me/videos", p);
//wait for image upload status and hopefully it returned a media ID on successful image upload
while (uploadedImgID == "")
{
//if image updload failed because of rate limit failure we can just abort rest of this
if (rateLimitErrorOccurred)
{
rateLimitErrorOccurred = false;
yield break;
}
yield return true;
}
//if video uploaded succesfully
if (uploadedImgID != null)
{
mediaIDs.Add (uploadedImgID);
var response = (JsonObject)fbClient.Get("/" + uploadedImgID + "?fields=status,published");
TruLogger.LogError("Video Status Details: " + response.ToString());
string vidStatus = (response["status"] as IDictionary<string, object>)["video_status"] as string;
while( vidStatus != "ready")
{
yield return new WaitForSeconds(5.0f);
response = (JsonObject)fbClient.Get("/" + uploadedImgID + "?fields=status,published");
TruLogger.LogError("Video Status Details: " + response.ToString());
vidStatus = (response["status"] as IDictionary<string, object>)["video_status"] as string;
}
TruLogger.LogError("Video ready");
yield return new WaitForSeconds(5.0f);
}
}
if (mediaIDs.Count > 0)
{
curPage = m_UserPages[FacebookFeedsList.GetInstance().ActiveFeed] as IDictionary<string, object>;
fbClient = new FacebookClient(curPage["access_token"].ToString());
JsonObject p = new JsonObject();
p.Add("message", message);
for (int i = 0; i < mediaIDs.Count; i++)
{
p.Add ("attached_media["+ i + "]", "{\"media_fbid\":\"" + mediaIDs[i] + "\"}");
}
fbClient.PostCompleted += OnPostUploadComplete;
fbClient.PostAsync("/me/feed", p);
}
}
void OnPostImageUploadComplete(object sender, FacebookApiEventArgs args)
{
//if successful store resulting ID of image on Facebook
try
{
var json = args.GetResultData<JsonObject>();
uploadedImgID = json["id"].ToString();
//TruLogger.LogError(json.ToString());
}
catch (Exception e)
{
apiPostStatusMessage = "FB post failed: media upload error";
TruLogger.LogError (e.Message);
TruLogger.LogError (e.InnerException.ToString());
FacebookOAuthException oEx = (FacebookOAuthException)(e.InnerException);
if (oEx != null) {
TruLogger.LogError ("Error Type: " + oEx.ErrorType);
TruLogger.LogError ("Error Code: " + oEx.ErrorCode);
TruLogger.LogError ("Error Subcode: " + oEx.ErrorSubcode);
apiAbortErrorCode = oEx.ErrorCode;
if (apiAbortErrorCode == 32 || apiAbortErrorCode == 4)
{
rateLimitErrorOccurred = true;
apiPostAbortErrorMessage = "WHOOPS! Looks like you have exceeded the daily API rate quota for one or more of your feeds. You may have to wait between 1-24 hours until Facebook replenishes your balance for these feeds: \n\n" + e.InnerException.ToString ();
}
else
{
rateLimitErrorOccurred = false;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
else
{
rateLimitErrorOccurred = false;
apiAbortErrorCode = -1;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
uploadedImgID = null;
}
}
//generic call back for any post calls
void OnPostUploadComplete(object sender, FacebookApiEventArgs args)
{
try
{
var json = args.GetResultData();
TruLogger.LogError(json.ToString());
apiPostStatusMessage = "FB post successfully submitted";
//FacebookPostStatusUpdatedEvent.Invoke("FB post successfully submitted");
}
catch (Exception e)
{
apiPostStatusMessage = "FB post failed to submit";
//FacebookPostStatusUpdatedEvent.Invoke("FB post failed to submit");
TruLogger.LogError (e.Message);
TruLogger.LogError (e.InnerException.ToString());
FacebookOAuthException oEx = (FacebookOAuthException)(e.InnerException);
if (oEx != null) {
TruLogger.LogError ("Error Type: " + oEx.ErrorType);
TruLogger.LogError ("Error Code: " + oEx.ErrorCode);
TruLogger.LogError ("Error Subcode: " + oEx.ErrorSubcode);
apiAbortErrorCode = oEx.ErrorCode;
if (apiAbortErrorCode == 32 || apiAbortErrorCode == 4)
{
rateLimitErrorOccurred = true;
apiPostAbortErrorMessage = "WHOOPS! Looks like you have exceeded the daily API rate quota for one or more of your feeds. You may have to wait between 1-24 hours until Facebook replenishes your balance for these feeds: \n\n" + e.InnerException.ToString ();
}
else
{
rateLimitErrorOccurred = false;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
else
{
rateLimitErrorOccurred = false;
apiAbortErrorCode = -1;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
}
Facebook doesn't directly allow to upload multiple videos or photos with videos on the business page. However, it is possible on a personal page so as an alternate solution you can create a post on a personal page and share it on the business page.
Check this video for more information: https://www.youtube.com/watch?v=AoK_1S71q1o

How do I get friends Faceook ID from App Request deep link using FB.GetAppLink in Unity?

I am using Unity 5.4 with the latest Facebook API (7.8) for this.
I am trying to find out what my friends Facebook ID is after clicking a Game Request they sent me. I have looked into and have been using FB.GetAppLink but it doesnt appear to give me the friends Facebook ID, only my Facebook ID and the games ID.
I am needing this information so that after accepting their challenge I can send them back a gift if I was successful.
Thanks
Found the answer after umping through a lot of hoops...
public void GetDeepLink ()
{
FB.GetAppLink(DeepLinkCallBack);
}
public void DeepLinkCallBack(IAppLinkResult result)
{
if (string.IsNullOrEmpty(result.Error))
{
IDictionary<string, object> dict = result.ResultDictionary;
if (dict.ContainsKey("target_url"))
{
string url = dict["target_url"].ToString();
string keyword = "request_ids=";
int k = 0;
while (k < url.Length - keyword.Length && !url.Substring(k, keyword.Length).Equals(keyword))
k++;
k += keyword.Length;
int l = k;
while (url[l] != '&' && url[l] != '%')
l++;
string id = url.Substring(k, l - k);
FB.API("/" + id + "_" + AccessToken.CurrentAccessToken.UserId, HttpMethod.GET, DeepLinkCallBackCallBack);
}
else
{
Debug.Log("Applink Error :" + result.Error);
}
}
}
void DeepLinkCallBackCallBack(IGraphResult result)
{
Debug.Log("Request callback");
Debug.Log("========================");
if (string.IsNullOrEmpty(result.Error))
{
IDictionary<string, object> dict = result.ResultDictionary;
if (dict.ContainsKey("from"))
{
IDictionary<string,object> from = dict["from"] as Dictionary<string, object>;
if (from.ContainsKey("name"))
{
Debug.Log(from["name"]);
deepLinkUserName = from["name"].ToString();
}
if (from.ContainsKey("id"))
{
deepLinkUserName = from["name"].ToString();
FB.API("/" + dict["id"], HttpMethod.DELETE, null);
}
}
}
else
{
Debug.Log("Error in request:" + result.Error);
}
}

facebook sdk 7.2 unity 5.2 profile picture pulls though in the editor but not on the facebook canvus?

I have 2 problems currently
Im using unity 5.2.0 and the Facebook unity sdk 7.2
My unity is set to PC build (I will explain why just now)
I have been following the grey zoned tutorials and adapting them where needed for the new SDK. In my unity editor I currently have a place for my profile pic, the username, share and invite buttons along with the Facebook login button. When I run the project, it runs through everything perfectly. It gets the profile picture and the username and puts them where they need to be, the share and invite buttons post in the log that they are working so that's fine.
My first problem is:
When I put my editor in web player build, I always get this error when i try to log in. Any advice on fixing this part?
ArgumentException: Cannot overwrite header: User-Agent
UnityEngine.WWW.CheckSecurityOnHeaders (System.String[] headers) (at
C:/buildslave/unity/build/Runtime/Export/WWW.cs:71)
UnityEngine.WWW..ctor (System.String url, System.Byte[] postData,
System.Collections.Generic.Dictionary`2 headers) (at
C:/buildslave/unity/build/artifacts/generated/common/runtime/UtilsBindings.gen.cs:125)
Facebook.Unity.AsyncRequestString+c__Iterator1.MoveNext () (at
Assets/Facebook/Scripts/Utils/AsyncRequestString.cs:100)
My second problem is:
I build my project (web player build) and upload it to my hosted server, then when I hop on Firefox or Internet Explorer and go to my app on the Facebook canvas it loads up, but the profile pic and username do not appear. The sharing and invites work however. Its only the pic and name that do not pull through.
I'm going to put all my code in so that you can see exactly what I have done.
Sorry I'm very new to coding so it probably looks terrible.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using UnityEngine.UI;
using System;
public class FBholder : MonoBehaviour
{
public GameObject UIFBIsLoggedIn;
public GameObject UIFBIsNotLoggedIn;
public GameObject UIFBAvatar;
public GameObject UIFBUserName;
public GameObject ErrorText;
public Text errorText;
private Dictionary<string, string> profile = null;
void Awake()
{
FB.Init (SetInit, OnHideUnity);
}
private void SetInit()
{
errorText = ErrorText.GetComponent<Text>();
Debug.Log ("FB Init done.");
//LOG: Error Text
errorText.text = "FB Init done.";
Debug.LogWarning("LOG "+ errorText.text);
if (FB.IsLoggedIn)
{
DealWithFBMenus(true);
Debug.Log ("FB Logged In.");
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "FB Logged In.";
Debug.LogWarning("LOG "+ errorText.text);
}else{
DealWithFBMenus(false);
FindTheStupidErrorLog();
errorText.text = "FB Not Logged In.";
Debug.LogWarning("LOG "+ errorText.text);
}
}
private void OnHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale = 0;
}else{
Time.timeScale = 1;
}
}
public void FBlogin ()
{
var perms = new List<string>(){"public_profile", "email",};
FB.LogInWithReadPermissions(perms, AuthCallback);
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "FB Logged In.";
Debug.LogWarning("LOG "+ errorText.text);
}
private void AuthCallback (ILoginResult result)
{
if (FB.IsLoggedIn) {
DealWithFBMenus(true);
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log(perm);
}
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "AuthCallback if";
Debug.LogWarning("LOG "+ errorText.text);
} else {
DealWithFBMenus(false);
Debug.Log("User cancelled login");
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "AuthCallback else";
Debug.LogWarning("LOG "+ errorText.text);
}
}
void DealWithFBMenus(bool isLoggedIn)
{
if(isLoggedIn)
{
UIFBIsLoggedIn.SetActive (true);
UIFBIsNotLoggedIn.SetActive (false);
FB.API (Util.GetPictureURL("me", 128, 128), HttpMethod.GET, DealWithProfilePicture);
FB.API ("/me?fields=id,first_name", HttpMethod.GET, DealWithUserName);
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "running deal with menu If";
Debug.LogWarning("LOG "+ errorText.text);
}else{
UIFBIsLoggedIn.SetActive (false);
UIFBIsNotLoggedIn.SetActive (true);
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "running deal with menu else";
Debug.LogWarning("LOG "+ errorText.text);
}
}
void DealWithProfilePicture (IGraphResult result)
{
if(result.Error != null)
{
Debug.Log ("Problem getting Pic");
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "Profile Pic Error";
Debug.LogWarning("LOG "+ errorText.text);
FB.API (Util.GetPictureURL("me", 128, 128), HttpMethod.GET, DealWithProfilePicture);
return;
}
Image UserAvatar = UIFBAvatar.GetComponent<Image>();
UserAvatar.sprite = Sprite.Create (result.Texture, new Rect(0,0,128,128), new Vector2(0,0));
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "Profile Pic loaded";
Debug.LogWarning("LOG "+ errorText.text);
}
void DealWithUserName (IGraphResult result)
{
if(result.Error != null)
{
Debug.Log ("Problem getting Pic");
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "UserName didnt loaded";
Debug.LogWarning("LOG "+ errorText.text);
FB.API ("/me?fields=id,first_name", HttpMethod.GET, DealWithUserName);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
Text UserMsg = UIFBUserName.GetComponent<Text>();
UserMsg.text = "Hello, " + profile["first_name"];
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "UserName loaded";
Debug.LogWarning("LOG "+ errorText.text);
}
public void ShareWithFriends()
{
if (!FB.IsLoggedIn)
{
FBlogin();
Debug.Log ("not logged in to share");
}else {
Uri contentUri = new Uri("http://apps.facebook.com/" +FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? AccessToken.CurrentAccessToken.UserId : "guest"));
FB.ShareLink(
contentURL: contentUri,
contentTitle: "Me Testing the FB SDK",
contentDescription: "I wonder where this shows?",
photoURL: new Uri("https://dragondigital.co.za/fb_7.1_test/mascotOne.png"),
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!");
}
}
public void InviteFriends()
{
FB.AppRequest(
message: "This is the Invite Message",
title: "This is the Invite Title."
);
print ("Invite prob worked");
//LOG: Error Text
FindTheStupidErrorLog();
errorText.text = "Invite prob worked";
}
public void FindTheStupidErrorLog()
{
if(errorText == null)
{
errorText = ErrorText.GetComponent<Text>();
}
}
}
Yes i know there is ALOT of redundant error logging but that will be taken out later :)
Any help you guys can give will be much appreciated :)

Using Prime31 and Facebook GraphAPI to upload a Photo on a Facebook-Page

Using Prime31 i can successfully upload an image to my own wall calling
public void postPhoto(byte[] photoBytes){
Facebook.instance.postImage( photoBytes, "my message", completionHandlerUploadPhoto );
}
But now i want to post the same picture to an album of a Facebook-Page. I tried calling this function i've written:
public void postToFatFishPage(byte[] photoBytes){
Dictionary<string, object> arguments = new Dictionary<string, object>();
arguments.Add("access_token", FacebookAndroid.getAccessToken());
arguments.Add("message", "my message");
arguments.Add("image", photoBytes);
Facebook.instance.graphRequest("/"+facebookPageID+"/photos", HTTPVerb.POST, arguments, ( string error, object obj ) =>
{
Debug.Log ("In Callback postToFatFishPage");
// if we have an error we dont proceed any further
if( error != null ){
Debug.Log("Error posting Photo to FatFish FB-Page: " + error);
return;
}
Debug.Log("No error");
});
}
The Callback function says that there is no error but the Facebook Page i am posting to says there is an error by having no uploaded picture.
I am logging in with the following rights:
FacebookAndroid.loginWithPublishPermissions( new string[] { "email", "user_birthday" } );
Maybe i have to add more rights?
Hope Someone can help me!
EDIT
I also tried out to take an album_id instead of the page_id but neither of it works.
Theres is still no error... I printed out the dictionary of the callback:
{
[id] = <some long number>,
[post_id] = <some even longer number with a underline in center>,
}
I don't know what i did exactly but know it is magically working... (mondays...)
That's the function:
public void postToFatFishPage(byte[] photoBytes){
Dictionary<string, object> arguments = new Dictionary<string, object>();
arguments.Add("access_token", FacebookAndroid.getAccessToken());
arguments.Add("message, myMessage);
arguments.Add("image", photoBytes);
Facebook.instance.graphRequest("/"+pageID+"/photos/", HTTPVerb.POST, arguments, ( string error, object obj ) =>
{
// if we have an error we dont proceed any further
if( error != null ){
Debug.Log("Error posting Photo to FatFish FB-Page: " + error);
return;
}
Debug.Log("SUCCESS!");
});
}
I hope i there is someone i could help :)