How to upload video with Facebook graph API - facebook

I've been struggling for weeks to get figure out how to upload video using the graph api. I've gone through all the documentation and i just don't understand what i must do to get a correct response from the graph api before i write the code. I've included an image.
Can someone just tell me like a child what I must put in exactly?

Figured out how to use graph api with c# for unity.
you can post a comment and post a video.
the url given is just an open video that was available, choose your own if you want, or if it becomes unavailable in the future.
enjoy!
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Facebook.MiniJSON;
public class FBVideoPost : MonoBehaviour {
// Use this for initialization
void Start () {
// this is to post string
postStatus ();
//this is to post video
this.StartCoroutine(this.StartVideoUpload());
}
void postStatus()
{
var formdata = new Dictionary<string, string>();
formdata.Add ("message", "This is my third post!");
FB.API("/me/feed", HttpMethod.POST, delegate (IGraphResult callback){
Debug.Log ("This is a test!");
},formdata);
}
private IEnumerator StartVideoUpload()
{
yield return new WaitForEndOfFrame();
WWW www = new WWW("http://techslides.com/demos/sample-videos/small.mp4");
while(!www.isDone) {
yield return null;
Debug.Log("progress : "+www.progress);
}
Debug.Log("size : "+www.size);
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("file", www.bytes, "Video.MOV","multipart/form-data");
wwwForm.AddField("title", "Hello World");
wwwForm.AddField("description", "How you doing?");
FB.API("me/videos", HttpMethod.POST, UploadFinish, wwwForm);
}
private void UploadFinish(IGraphResult result) {
Debug.Log("result : "+result.ToString()+" , error : "+result.Error);
}
}

I will post another forum thread where you answered yourself and that helped me in addition to your answer here.
http://answers.unity3d.com/questions/1167534/how-to-send-file-local-path-using-wwwform-on-ios-a.html
In short, for anyone looking to "Upload Videos using the FB SDK from iOS", follow Luke's answer and add the following:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Facebook.MiniJSON;
public class FBVideoPost : MonoBehaviour {
// Use this for initialization
void Start () {
// this is to post string
postStatus ();
//this is to post video
this.StartCoroutine(this.StartVideoUpload());
}
void postStatus()
{
var formdata = new Dictionary<string, string>();
formdata.Add ("message", "This is my third post!");
FB.API("/me/feed", HttpMethod.POST, delegate (IGraphResult callback){
Debug.Log ("This is a test!");
},formdata);
}
private IEnumerator StartVideoUpload()
{
yield return new WaitForEndOfFrame();
///ADD THIS
//this is the path to your file.
String VideoLocStr = Application.persistentDataPath + "Your_Video.mov"
String pathForIOS = VideoLocStr.Replace (" ","%20");
WWW www = new WWW(pathForIOS);
///
while(!www.isDone) {
yield return null;
Debug.Log("progress : "+www.progress);
}
Debug.Log("size : "+www.size);
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("file", www.bytes, "Your_Video.mov","multipart/form-data");
wwwForm.AddField("title", "Hello World");
wwwForm.AddField("description", "How you doing?");
FB.API("me/videos", HttpMethod.POST, UploadFinish, wwwForm);
}
private void UploadFinish(IGraphResult result) {
Debug.Log("result : "+result.ToString()+" , error : "+result.Error);
}
}
Thanks, Luke.
Good luck to everyone.

Related

Unity Remote notification authorization request not showing up

I have a basic unity scene that involves a button which is linked to an OnClick method. I know this part works because I have the debug.log that tells me.
I tried looking all over the internet and stack overflow and couldn't find an answer to my problem.
The part that I suspect is the problem is the authorization request. I'm using Unity simulator for testing as well as the remote 5 app. When I play my project there is no request on either testing form for notifications. So my main question is why does the authorization request fail. I am using the mobile notifications package offered by Unity and have tried messing around with the settings there such as request authorization on app launch.
Part of what confuses me is that I got most of the code straight from Unity documentation.
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Notifications.iOS;
using UnityEngine;
public class NotificationManager : MonoBehaviour
{
private void Start()
{
StartCoroutine(RequestAuthorization());
}
IEnumerator RequestAuthorization()
{
using (var req = new AuthorizationRequest(AuthorizationOption.Alert | AuthorizationOption.Badge, true))
{
Debug.Log(req.IsFinished);
while (!req.IsFinished)
{
yield return null;
};
string res = "\n RequestAuthorization:";
res += "\n finished: " + req.IsFinished;
res += "\n granted : " + req.Granted;
res += "\n error: " + req.Error;
res += "\n deviceToken: " + req.DeviceToken;
Debug.Log(res);
}
}
public void OnClick()
{
Debug.Log("Sending Notif");
SendNotification();
}
private void SendNotification()
{
var timeTrigger = new iOSNotificationTimeIntervalTrigger()
{
TimeInterval = new TimeSpan(0, 0, 1),
Repeats = false
};
var notification = new iOSNotification()
{
// You can specify a custom identifier which can be used to manage the notification later.
// If you don't provide one, a unique string will be generated automatically.
Identifier = "testNotification",
Title = "Test Notification",
Body = "Testing the notification capability",
Subtitle = "What does the subtitle look like",
ShowInForeground = true,
ForegroundPresentationOption = (PresentationOption.Alert | PresentationOption.Sound),
CategoryIdentifier = "category_a",
ThreadIdentifier = "thread1",
Trigger = timeTrigger,
};
iOSNotificationCenter.ScheduleNotification(notification);
}
}

How to instantiate objects in a specified place in unity?

I have an AR app that displays objects when it detects a QR code. The way I do it is with an empty object called model caller that has an script that instantiates a model, this is the script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Load_Models: MonoBehaviour
{
// Start is called before the first frame update
[Serializable]
public class PlaceModel
{
public string Clave = "";
}
public GameObject[] model;
public string[] clave_modelos;
public string URL;
public GameObject ModeloUI;
public PlaceModel placeModel;
Dictionary<string, GameObject> strGO = new Dictionary<string, GameObject>();
public void Start()
{
StartCoroutine(GetRequest(URL));
for (int i = 0; i < model.Length; i++)
{
strGO.Add(clave_modelos[i], model[i]);
}
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string jsonForm = uri;
if (webRequest.isNetworkError)
{
Debug.Log("Error loading");
}
else
{
try
{
PlaceModel model_1 = JsonUtility.FromJson<PlaceModel>(webRequest.downloadHandler.text);
Instantiate(strGO[model_1.Clave], new Vector3(0, 0, 0), Quaternion.identity, transform); //instantiates the model
Debug.Log("Loaded");
}
catch
{
Debug.Log("Error in connection");
}
}
}
}
}
and this is what happens when I detect more than 1 QR (it also happens with only one, just without the models "fusing" with each other):
Explanation: It should display 3 models, 1 simple street (the white block) and 2 "no model" 3d texts, but, the idea is for the models to appear "attached" (I don't know how to word it) to the QR code. And I tried to do it by having model caller as a child of the ImageTarget and with model caller being in the dead center of the imagetarget, also with new Vector3(0, 0, 0).
Is there a way to do this?
I know that I can do it by simply using the prefab by itself instead of a script, but I need for the models to change depending on a website (which I already did).
I'm using EasyAR 3 for this
If I got you right, try to change Instantiate line this way:
Instantiate(strGO[model_1.Clave], transform.position, Quaternion.identity, transform);
Also, maybe, you dont need to set parent transform, it depends from your implementation.

Invalid Credential When Sign In Facebook SDK To Firebase/Unity

I try to implement Facebook Authentication on my Unity project. So, after experimenting a few things i could make the Email Authentication works fine. But, when i tried to implement the Facebook Authentication it said "Invalid Credential". Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using Facebook.Unity;
public class facebookAuth : MonoBehaviour
{
private void Awake() {
FB.Init(initCallBack,OnUnityHide);
}
void initCallBack(){
if(!FB.IsInitialized)
FB.ActivateApp();
}
void OnUnityHide(bool show){
if(show)
FB.ActivateApp();
}
public void facebookLogin(){
if(FB.IsLoggedIn){
FB.LogOut();
}
var perms = new List<string>(){"email","public_profile"};
FB.LogInWithReadPermissions(perms,facebookResult);
}
void facebookResult(ILoginResult result){
if(FB.IsLoggedIn){
AccessToken token = result.AccessToken;
Credential credential = FacebookAuthProvider.GetCredential(token.TokenString);
firebaseFacebook(credential);
}
}
void firebaseFacebook(Credential token){
FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(token).ContinueWith(task=>{
if(task.IsCanceled){
Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
errorMessage("Canceled : ",(AuthError)e.ErrorCode);
}
if(task.IsFaulted){
Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
errorMessage("Faulted : ",(AuthError)e.ErrorCode);
}
Debug.Log(task.Result.DisplayName + " " + task.Result.UserId);
});
}
void errorMessage(string str, AuthError error)
{
string msg = error.ToString();
print(str+msg);
}
}
Your code looks correct to my reading. Make sure Facebook is enabled in the Firebase Console and the proper credentials have been filled out:
(I forget this all the time, especially if I have to enter things like the App Secret).
If this doesn't help, it would be useful to have any additional logging (or a copy of the error message) if possible.
--Patrick

Unity deserializing an object in another project

I am creating a tool that helps the artist in my studio design their UI easily, and then give them the ability to export the UI to the developers to use in their projects.
Long story short, I followed this tutorial: What is the best way to save game state?
and it worked correctly when I wrote everything in the same script.
However when I opened another unity project to import the data, it stopped working correctly. It would read the file, but then the spawnObject variable which is supposed to be instantiated stays null.
The class I use here is called UIdata, and it has only one gameobject variable which is inputObject, and the class is exactly the same as the one I am exporting from the other project
I am not quite sure why it is not working, can deserialization work if its importing something from another project?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System;
public class DataSaver
{
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Application.streamingAssetsPath + "/newUICorrect.txt";
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
public static T loadData<T>(string dataFileName)
{
string tempPath = Application.streamingAssetsPath + "/newUICorrect.txt";
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
else
{
Debug.Log("found file");
}
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
string jsonData = Encoding.ASCII.GetString(jsonByte);
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
}
[System.Serializable]
public class UIData
{
public GameObject inputObject;
}
public class LoadingScript : MonoBehaviour
{
private GameObject objectToSpawn;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
importObject();
}
}
public void importObject()
{
UIData loadedData = new UIData();
loadedData = DataSaver.loadData<UIData>("UI");
objectToSpawn = loadedData.inputObject;
if (loadedData == null)
{
return;
}
print(objectToSpawn);
}
}
#Programmer is correct, you cannot serialize engine types. There are several ways to go about resolving your issue. The first is to rebuild your gameobject by serializing its MonoBehaviour components in the following manner (pseudocode):
public GameObject TestSaveAndLoadComponent(MyMonoBehaviour myComponent, GameObject objectToLoadComponentOnto){
// convert component to Json
string jsonString = JsonUtility.ToJson(myComponent);
// Pretend to save the json string to File
string directory = "TestDirectory";
string file = "objectFile";
SaveLoadData.SaveString(directory,file,objectJson);
// load string from file
string loadString = SaveLoadData.LoadString(directory,file);
// add a MonoBehaviour component to the object so that it can be
// overwritten by the JsonUtility
MyMonoBehaviour componentToOverwrite = objectToLoadComponentOnto.AddComponent<MyMonoBehaviour>();
JsonUtility.FromJsonOverwrite(loadString, componentToOverwrite);
return newObject;
}
JsonUtility may not provide a deep copy of your your monoBehaviour class, I don't use it much. It's pretty bare bones, and if it doesn't meet your needs, there's always Json.Net for unity.
All that being said, you shouldn't need to serialize gameObjects or monobehaviours if you structure your code in the proper way, using an Model-view-controller pattern. In such a case you would only need to serialize very simple classes that define the Model for the UI, and then the your view classes would rebuild the ui in a separate scene or project from the given model.

IP Camera in Unity3D

I'm attempting to get a view in Unity3D with an IP camera. Only when I use the URL to access the camera with a script(see below) it gives the 401 Unauthorized error. Now I need to login with a password and username, both admin.
But I'm not sure how to put that in the URL, any help with that? See the code below on what I have so far.
//#pragma strict
// http://docs.unity3d.com/Documentation/ScriptReference/WWW.LoadImageIntoTexture.html
var url = "http://192.168.1.30/admin/view.cgi?profile=2&language=en";
function Start () {
// Create a texture in DXT1 format
// NOTE: you may want to experiment with different texture formats, specially in a web context
// https://docs.unity3d.com/Documentation/ScriptReference/TextureFormat.html
renderer.material.mainTexture = new Texture2D(4, 4, TextureFormat.DXT1, false);
Debug.Log(adress);
Debug.Log(url);
while(true) {
// Start a download of the given URL
var www = new WWW(url);
// wait until the download is done
yield www;
// assign the downloaded image to the main texture of the object
www.LoadImageIntoTexture(renderer.material.mainTexture);
}
}
==============================================
So now I am using the WWWForm.Headers. Yet when I put it in my code, it gives me a "A field initializer cannot reference the field method or property"
The code is:
public class SEMTEX : MonoBehaviour {
// Use this for initialization
//void Start() {
public WWWForm form = new WWWForm ();
public string headers = form.headers;
public byte[] rawData = form.data;
public string url = "http://192.168.1.101/snapshot.cgi";
public WWW www = new WWW (url, rawData, headers);
//}
IEnumerator Update (){
form.AddField ("name", "value");
headers ["Authorization"] = "Basic " + System.Convert.ToBase64String (System.Text.Encoding.ASCII.GetBytes ("admin:admin"));
yield return www;
}
Any idea what's going on?
Use WWWForm.headers. The example in the docs is doing HTTP basic auth.
Also, if you're planing to update the image often, using an uncompressed texture like TextureFormat.RGB24 should be much faster.
The unity docs was quite outdated, so here's the complete script that continuously updates a webcam and draws it on a screen:
using UnityEngine;
using System.Collections;
public class HttpWebcam : MonoBehaviour {
public string uri;
public string username;
public string password;
Texture2D cam;
public void Start() {
cam=new Texture2D(1, 1, TextureFormat.RGB24, false);
StartCoroutine(Fetch());
}
public IEnumerator Fetch() {
while(true) {
Debug.Log("fetching... "+Time.realtimeSinceStartup);
WWWForm form = new WWWForm();
form.AddField("dummy", "field"); // required by WWWForm
WWW www = new WWW(uri, form.data, new System.Collections.Generic.Dictionary<string,string>() { // using www.headers is depreciated by some odd reason
{"Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username+":"+password))}
});
yield return www;
if(!string.IsNullOrEmpty(www.error))
throw new UnityException(www.error);
www.LoadImageIntoTexture(cam);
}
}
public void OnGUI() {
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height), cam);
}
}
To run just drag into a GameObject and provide any URI containing a PNG or JPEG. It can also access resources that arent password protected (password is ignored then). For an example you can use: http://www.sudftw.com/imageppc.php.
Adding on to Krzysztof's answer, replace the OnGUI() method to overlay the camera feed onto an in-game object (eg. like an in-game television screen), instead of drawing it on the whole screen.
public GameObject displayPlane;
public void OnGUI()
{
displayPlane.GetComponent<Renderer>().material.mainTexture = cam;
}