i am trying to upload a video to the users Facebook wall i have the FacebookMobile.uploadVideo in place and appears to to be fine but am getting the following error from facebook:
(#353) You must select a video file to upload.
i think the problem is in accessing the video file for some reason.
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook"+ accessCamera.filePath);
var videoInfo:Object = new Object;
videoInfo.title = "test upload on FB api",
videoInfo.description = accessCamera.filePath,
videoInfo.fileName = accessCamera.filePath;
videoInfo.video = accessCamera.filePath;
FacebookMobile.uploadVideo('me/videos', onComplete, videoInfo);
}
private function onComplete( result:Object, fail:Object ):void
{
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
accessCamera.filepath is the var where the video file is located on the device and looks like this when traced : file:///mnt/sdcard2/DCIM/Camera/VID_20140304_105813.mp4
Am I accessing the file correctly, does it need to be loaded by the app or is a path fine.
any help would be greatly appreciated.
the issue is i was passing a string variable containing the file location into the params object and the FacebookMobile.uploadVideo requires either a fileReferance or byteArray.
Related
i am try to download asset bundle from an url but the request keep on cancelling after downloading 63kb. Can anyone explain to me why this may be happening?
My Code :
public IEnumerator DL()
{
string downloadlink = "https://drive.google.com/file/d/1OGyrB4-MQfo-HVom9ENvV4dn312_wL4Q/view?usp=sharing";
string filepath = Application.persistentDataPath + "/electroplatingNN";
//Download
UnityWebRequest dlreq = new UnityWebRequest(downloadlink);
dlreq.downloadHandler = new DownloadHandlerFile(filepath);
dlreq.timeout = 15;
UnityWebRequestAsyncOperation op = dlreq.SendWebRequest();
while (!op.isDone)
{
//here you can see download progress
Debug.Log(dlreq.downloadedBytes / 1000 + "KB");
yield return null;
}
if (dlreq.isNetworkError || dlreq.isHttpError)
{
Debug.Log(dlreq.error);
}
else
{
Debug.Log("download success");
}
dlreq.Dispose();
yield return null;
}
As already mentioned in the comments the issue is not in the UnityWebrequest but rather Google Drive doesn't simply download your file as you expect.
Instead the data you download is actually only the web page which would allow you to download it. If I simply open your file in a browser I get a page looking like this
where I now could download your file.
There are packages like this or this which implement the necessary stuff for actually download files from Google Drive API in Unity.
I am using Unity 5.5.2f1 pro and facebook's SDK v 7.9.4
I have a script which after login (managed in a previous scene) sends an API request to FB asking for friends, name and email and sends that info as a POST to a php website.
code:
[Serializable]
public struct FBData {
public string first_name;
public string email;
public string friends;
public string id;}
public class UserManagement : MonoBehaviour {
string urlSaveUserData="some php website";
public Text testTxt;
FBData parsedData;
// Use this for initialization
void Start () {
//Check if it's the first time the user is opening the app.
if (UserInfo.FIRST_TIME) {
//update text (only used for testing, should be removed in production.)
testTxt.text = "Your user id is: " + UserInfo.ID;
//Perform FB.API call to get User Data.
getUserData ();
//Save in SQL table. (won't get here if line in getUserData() is active)
StartCoroutine ("saveUserData");
} else {
//do something else.
}
note: Since this is meant for iOS I have to test it on a device so I'm using text in the screen to display info (think of it as a badly implemented print statement).
The problem: In my callback function for FB.API I write in the text Gameobject (aka testTxt) the parsed information from the response which is saved in the Custom UserInfo clss. It display's correctly but the code gets stuck there. It doesn't continue to the next function. HOWEVER, if I delete/comment that line and don't display anything in the text field. The codes does continue to the POST function BUT the information from the API call is not passed, i.e my custom class is empty (leading me to believe the callback function is not called at all).
public void getUserData(){
string query = "me?fields=first_name,email,friends";
FB.API (query, HttpMethod.GET, Apicallback, new Dictionary<string, string> ());
}
private void Apicallback(IGraphResult result){
//Parse Graph response into a specific class created for this result.
parsedData = JsonUtility.FromJson<FBData>(result.RawResult);
//Pass each field into UserInfo class.
UserInfo.EMAIL = parsedData.email;
UserInfo.FRIENDS = parsedData.friends;
UserInfo.NAME = parsedData.first_name;
UserInfo.FACEBOOKID = parsedData.id;
/*problem area, if I comment line below, then previous information is apparently not stored. If left as is then testTxt displays correct information but code gets stuck there. */
testTxt.text = "This is the info from USerInfoInside the APICallback: " + UserInfo.EMAIL + UserInfo.FRIENDS + UserInfo.FACEBOOKID;
}
The function below is to send info to php website, is there for illustrative purposes:
code:
public IEnumerator saveUserData() {
//get user info (this information is EMPTY if line in getUserData() is commented.
parsedData.id = UserInfo.FACEBOOKID;
parsedData.friends = UserInfo.FRIENDS;
parsedData.first_name = UserInfo.NAME;
parsedData.email = UserInfo.EMAIL;
//translate data into json
string JsonBodyData = JsonUtility.ToJson (parsedData);
//Custom web request (POST method doesnt seem to work very well, documentation example sends empty form)
var w = new UnityWebRequest(urlSaveUserData, "POST");
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(JsonBodyData);
w.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
w.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
w.SetRequestHeader("Content-Type", "application/json");
yield return w.Send();
//work with received data...}
Im stuck here any help is appreciated. Thanks!
Be sure to use EscapeURL when using strings directly for JSON or HTTP POST and GET methods. The lack of this treatment tends to screw things over, particulary in iOS platforms.
From what I can see, this code
string query = "me?fields=first_name,email,friends";
should instead be escaped as
string query = WWW.EscapeURL("me?fields=first_name,email,friends");
so characters like "?" won't get encoded as an URL symbol.
I'm assuming you don't need to do that for your illustrative example, because UnityWebRequest already escapes your POST request strings internally, but I can't fully confirm that.
I am using the facebook4j library for integrating facebook api in java. However, I face issues when I try to post a photo with a place attribute.
Media media = new Media(new File(<image-path-here>));
PhotoUpdate update = new PhotoUpdate(media);
update.message("photo upload test");
update.setPlace("Bangalore");
facebook.postPhoto(update);
But I get the following exception:SEVERE: Servlet.service() for servlet [post] in context with path [/Sample] threw exception [message - An unknown error has occurred.FacebookException{statusCode=500, errorType='OAuthException', errorMessage='An unknown error has occurred.', errorCode=1, errorSubcode=-1, version=2.2.0}
Turns out that without the 'setplace' its works completely fine. I am not sure if I am doing the right way and searched the web to get some samples as well. But could not find one, can anyone please suggest what am I doing wrong here? I can post the photo on facebook without setting the location but I need to set location for image.
Thanks
With my solution, I upload the image to server and upload that file to facebook. you can see the below example.
/**
* NOTE: Post Photo To Wall Facebook
* #param String idToObject
* #param File filePhoto (This is real file from server)
* #return List<String>
*/
public String postToWallPhoto(String idToObject, UploadedFile uploadedFile) {
PhotoUpdate photoUpdate = null;
try {
Media media=new Media(uploadedFile.getFile());
photoUpdate = new PhotoUpdate(media);
photoUpdate.message(postItem.getGroupMessage());
String idPost = facebook.postPhoto(idToObject, photoUpdate);
} catch (FacebookException e) {
e.printStackTrace();
}
return idPost;
}
Can you try this.
PostUpdate post= update = new PostUpdate("#Minh Nguyen")
.picture(new URL("Img_url"));
facebook.postFeed(id,post);
I'm creating a game for the Facebook Canvas using the official Facebook SDK. Despite using code directly from the Facebook Unity example, I cannot save nor load a score value. I receive no error or message whatsoever - A value of 0 is always returned when I attempt to retrieve the score. Everything else (logging in, posting to the news feed, etc.) is working fine - just not the score management. Also, this occurs both in the Unity editor and on the canvas itself.
I save the player's score like this:
public void SaveScore(int _score)
{
_fbScore = _score;
var _query = new Dictionary<string, string>();
_query["score"] = _fbScore.ToString();
FB.API("/me/scores", Facebook.HttpMethod.POST, delegate(FBResult r) { Util.Log("Result: " + r.Text); }, _query);
//FB.API ("/me/scores", Facebook.HttpMethod.POST, ScoreSaveCallBack, scoreData);
_hiScoreText.text = _fbScore.ToString();
}
I then try to retrieve the score with this method:
public void GetHighScore()
{
if (_fbIsInited)
FB.API ("/app/scores?fields=score,user.limit(20)", Facebook.HttpMethod.GET, GetScoreCallBack);
}
Callback method:
void GetScoreCallBack(FBResult _result)
{
try
{
List<object> _scoresList = Util.DeserializeScores(_result.Text);
foreach(object _score in _scoresList)
{
var _entry = (Dictionary<string,object>) _score;
var _user = (Dictionary<string,object>) _entry["user"];
string _userId = (string)_user["id"];
if (string.Equals(_userId, FB.UserId))
{
_fbScore = GetScoreFromEntry(_entry);
_hiScoreText.text = _fbScore.ToString();
Debug.Log("FB SCORE: + " + _fbScore);
}
}
}
catch (System.Exception _e)
{
Debug.Log(_e.Message);
}
}
As the score returned is always 0, I do not know whether the problem is with the save or load methods.
EDIT:
To make matters worse, out of nowhere, I've started getting these errors when I attempt to post the score:
You are trying to load data from a www stream which had the following error when downloading.
403 Forbidden
UnityEngine.WWW:get_text()
FBResult:get_Text()
FacebookManager:<SaveScore>m__0(FBResult) (at Assets/Scripts/Facebook/FacebookManager.cs:138)
Facebook.<Start>c__Iterator0:MoveNext()
I haven't made any changes to the code, they just started appearing every time!
Shouldn't you pass a numeric app id in this call instead of 'app'?
FB.API ("/123456789/scores?fields=score,user.limit(20)"
You can find your's app code at FacebookDeveloper dashboard, on your app's main panel - it's the 'application identifier'.
Have you also specified this number in unity Facebook|Facebook Settings|App id? That should fix your problems.
Do you have any idea? I am developing an app using Unity IDE and C#. Also, I'm using the social networking prime31 for my plugin with Facebook. I was able to get all the graphs and display it in my screen app, but since last week it didn't show the profile picture and my friend's picture, it just shows a plain question mark. Do you have any idea with regard to that?
But I was able to show the username and my friend's username. My app token is working, and I am using JSON data to get the data from the Facebook URL.
void Start()
{
getFB_ID();
}
void getFB_ID()
{
Facebook.instance.graphRequest( "me/", HTTPVerb.GET, ( error, obj ) =>
{
var ht = obj as Hashtable;
userId = ht["id"].ToString();
Debug.Log( "USER ID: " + userId);
string url = "http://graph.facebook.com/"+userId+"?fields=id,name,picture";
StartCoroutine(getURL(url));
});
}
IEnumerator getURL(string url)
{
WWW www = new WWW(url);
yield return www;
Debug.Log ("Heres the URL you are accessing: " + url);
ProfilePicDisplay(www.text);
public void ProfilePicDisplay(string jsonString)
{
JsonData jsonProfilePic = JsonMapper.ToObject(jsonString);
ConverterScript fbprofilepic;
MyPicture = new ArrayList();
{
fbprofilepic = new ConverterScript();
fbprofilepic.name = jsonProfilePic["name"].ToString();
fbprofilepic.picture = jsonProfilePic["picture"].ToString();
LoadProfilePic(fbprofilepic);
MyPicture.Add(fbprofilepic.name);
}
}
private void LoadProfilePic(ConverterScript profile)
{
string ProfilePic = "userAvatar";
GameObject profile_pic_holder = GameObject.Find(ProfilePic);
profile_pic_holder.SendMessage("LoadImage", profile);
}
was able to get the data in my logs, but the problem is it didnt load the image, it says:
You are trying to load data from a www stream which had the following error when downloading.
Could not resolve host: JsonData object (Domain name not found)
As of last week, October 3rd and detailed here: https://developers.facebook.com/blog/post/2012/10/03/platform-updates--operation-developer-love/
The picture endpoint no longer returns the picture URL in the string. It returns a dictionary and you have to change your parsing to get to it. So the data returned will look more like this:
{
"id": "1234567",
"name": "Your Name",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn1/your_picture.jpg",
"is_silhouette": false
}
}
}
In the latest LeanLoader, there is an automatic fix for the newly implimented Facebook endpoint abernathy mentioned, which allows you to load the image directly (with all the parsing of the json and other data handled by the engine). You can easily load profile images like this:
function Start () {
LeanLoader.load("https://graph.facebook.com/DentedPixel/picture?type=large&redirect=false", LLOptions().setOnLoad(onImageLoaded));
}
private function onImageLoaded( tex:Texture2D ){
Debug.Log("Your image texture ready to use! :"+tex);
}
There is also many other features that I think people will find helpful with LeanLoader (including caching of images/text/sound and a built-in JSON parser).
try this- fb sdk version-9.1.0
FB.API ("/me/picture?type=large", HttpMethod.GET, DisplayProfilePic);// API call
void DisplayProfilePic(IGraphResult result)
{
Image profilePic;
if (result.Texture != null)
{
profilePic = image1; // diplaying image
profilePic.sprite = Sprite.Create(result.Texture, new Rect(0, 0, result.Texture.width, result.Texture.height), new Vector2());
}
}