Upload picture to facebook from unity - android

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());
}

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.

Related

Screenshot image is not showing for Twitter share on Android device

I am having this issue which I hope you can help me solve. Basically I have set up twitter sharing on Corona SDK (using the social plugin) so that players can post their highscores. The game would save a JPEG image and then Twitter loads this inside the message when sharing.
Now the issue is that on iOS, this works perfectly, but on Android devices the image doesn't show in the message body. Can you please help me as I have been banging my head trying to figure this out but have gotten nowhere. Cheers.
Here is my code to take the screenshot:
function takePhoto()
local baseDir = system.DocumentsDirectory
display.save(overlayGroup, "myScreenshot.jpg", baseDir )
print("PIC SAVED")
end
And this these are the options for sharing:
local options = {
service = "twitter",
message = "You got a highscore! ",
listener = tweetCallback,
image = {
baseDir = system.DocumentsDirectory,
filename = "myScreenshot.jpg"
}
}
And these are the code in build.settings
android =
{
versionCode = "1",
googlePlayGamesAppId = "xxxxxxxxxx", --My code is here
usesPermissions =
{
"android.permission.INTERNET",
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.ACCESS_WIFI_STATE",
"android.permission.ACCESS_NETWORK_STATE",
},
}

Xamarin FacebookClient

I am using Xamarin Forms and want to integrate Facebook in android app. I want to pull the feed from a page like https://www.facebook.com/HyundaiIndia
I have installed Xamarin.Facebook from Nuget. It doesn't have a FacebookClient object as mentioned in here: https://components.xamarin.com/gettingstarted/facebook-sdk
Then I found the Xamarin.Facebook and Xamarin.FacebookBolts namespaces which I included, but I still didn't get FacebookClient. Instead I found Xamarin.Facebook.XAndroid.Facebook and I created an instance:
Xamarin.Facebook.XAndroid.Facebook fb = new Xamarin.Facebook.XAndroid.Facebook(FacebookAppId);
But this object doesn't have GetTaskAsync. How do I pull down the feeds in Xamarin?
I had the same experience trying following the article you mentioned.
The component created by Outercurve Foundation (Facebook.dll version 6.2.1)
needs that you reference Facebook.dll and you include it in your file like this:
using Facebook;
Don't confuse it with:
using Xamarin.Facebook;
EDIT
I finally found a bit of time for a more complete answer and since the example on the link
doesn't specify how to obtain the AccessToken (called userToken in the facebook-sdk component page example linked in the question) I'm posting one of the possible solutions.
This one works for me and doesn't require any other library or component (but the one already mentioned in the question).
using Xamarin.Auth;
using Facebook;
string FaceBookAppId = "YOUR_FACEBOOK_APP_ID";
string AccessToken;
string OauthTokenSecret;
string OauthConsumerKey;
string OauthConsumerSecret;
void GetFBTokens()
{
var auth = new OAuth2Authenticator(FaceBookAppId,
"",
new Uri("https://m.facebook.com/dialog/oauth/"),
new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
eventArgs.Account.Properties.TryGetValue("access_token", out AccessToken);
eventArgs.Account.Properties.TryGetValue("oauth_token_secret", out OauthTokenSecret);
eventArgs.Account.Properties.TryGetValue("oauth_consumer_key", out OauthConsumerKey);
eventArgs.Account.Properties.TryGetValue("oauth_consumer_secret", out OauthConsumerSecret);
}
};
}
//Now we can use the example of the link.
void PostToMyWall ()
{
FacebookClient fb = new FacebookClient (AccessToken);
string myMessage = "Hello from Xamarin";
fb.PostTaskAsync ("me/feed", new { message = myMessage }).ContinueWith (t => {
if (!t.IsFaulted) {
string message = "Great, your message has been posted to you wall!";
Console.WriteLine (message);
}
});
}
There are 2 editions of Facebook SDK, one is binding for official SDK, another is from Outercurve Foundation.
Looks like you're using this one: the "official" binding , so check the documentation on this link.

AxSU3D Android Facebook Plugin - "The parameter app_id is required"

I'm using AxSU3D's Android plugin in a Unity project. When I try to use the Facebook Login method, I get an error that says "The parameter app_id is required"
I have posted my code below. I have REPLACED the string "fbAppID" with the actual ID. This is just the sample script that came with the plugin that I am trying to use.
Any help will be appreciated
using UnityEngine;
using System.Collections;
using AxSAndroidPlugin.Core;
using AxSAndroidPlugin.Social.Facebook;
public class FacebookSample : MonoBehaviour {
public string fbAppID = "YOUR_FACEBOOK_APP_ID_HERE";
public GameObject picture;
//Texture2D tex;
void OnGUI () {
if(GUI.Button(GUIControls.GetButtonRect(1), "Init" ))
Facebook.Init(fbAppID);
if(GUI.Button(GUIControls.GetButtonRect(2), "Login" ))
Facebook.Login();
if(GUI.Button(GUIControls.GetButtonRect(3), "IsLoggedIn"))
Facebook.IsLoggedIn();
if(GUI.Button(GUIControls.GetButtonRect(4), "User Info")) {
Facebook.GetUserInfo();
}
if(GUI.Button(GUIControls.GetButtonRect(5), "Friends")) {
Facebook.GetFriendsList();
}
if (GUI.Button (GUIControls.GetButtonRect (6), "Load Profile Picture")) {
Facebook.LoadProfilePicture();
}
if (GUI.Button (GUIControls.GetButtonRect (7), "Get Profile Picture")) {
Texture2D tex = Facebook.GetProfilePicture();
picture.renderer.material.mainTexture = tex;
}
if(GUI.Button(GUIControls.GetButtonRect(8), "Send Request")) {
Facebook.SendRequest("This Plugin Rocks!");
}
if(GUI.Button(GUIControls.GetButtonRect(9), "Post To Timeline")) {
string name = "AxS Android Plugin";
string caption = "AxS Android Plugin for Unity";
string description = "A complete solution to all your Android native needs!";
string link = "http://www.axsu3d.com/";
string pictureLink = "http://www.axsu3d.com/DLs/axsu3dLogo.png";
Facebook.PostToTimeline(name, caption, description, link, pictureLink);
}
//Get the user's likes
if(GUI.Button(GUIControls.GetButtonRect(10), "User Likes")) {
Facebook.GetUserLikes();
}
//Logout of Facebook
if(GUI.Button(GUIControls.GetButtonRect(11), "Logout" ))
Facebook.Logout();
if(GUI.Button(GUIControls.GetButtonRect(12), "Back"))
Application.LoadLevel("CoreSample");
}
}
Firstly, wow. I didn't realize something I helped make would show up on SO.
The solution is quite simple, really. You probably did not use the "Merge Manifest" option.
You can find this option under "Tools/AxSU3D/Android/Merge Manifest". This will show a window where you can put in your Facebook app ID.
The option will create or merge a new AndroidManifest.xml file, which will also contain your Facebook App ID.
Try it out.

Unity Facebook SDK: post screenshot to wall not working

I am using Unity 4.5, the latest facebook sdk 6.0 and I am working on android right now but it should also work on iOS.
I am trying to take a screenshot and upload it to my wall, therefore I use the standard example scene from the facebook sdk.
Everything works fine when I use my private account as a test account, and it also works with the facebook app ID's of older projects (at least 1 year old). But with a normal account (no tester) and a new facebook app it is not working.
Do I have to do a full submission to use the "post an image to the users wall" function or am I doing something wrong?
My facebook app says "This app is public and available to all users" . So I guess it should work right?
I use this for login:
private void CallFBLogin()
{
FB.Login("email, publish_actions", LoginCallback);
}
void LoginCallback(FBResult result)
{
if (result.Error != null)
lastResponse = "Error Response:\n" + result.Error;
else if (!FB.IsLoggedIn)
{
lastResponse = "Login cancelled by Player";
}
else
{
lastResponse = "Login was successful!";
}
}
And this as screenshot method:
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();
textureTest = tex;
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "InteractiveConsole.png");
wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?");
FB.API("me/photos", Facebook.HttpMethod.POST, Callback, wwwForm);
}
Hope someone has a solution.
Thank you!
As per the docs. You need to submit your app for review if you require the publish_actions permission.
Review
If your app requests this permission Facebook will have to
review how your app uses it.
When requesting this permission via App Review, please make sure your
instructions are easily reproducible by our team.

Android(AIR/Actionscript) Cant return FB access_token from stageWebView

Im simply trying to get my users access token from FB using stageWebView. When i trace the output from the location change/changing events all i get are google/FB urls, none of which have the token.
Here is my code:
var webView:StageWebView = new StageWebView();
function onChanging(e:LocationChangeEvent):void {
trace(e.location);
e.preventDefault();
webView.loadURL(e.location);
webView.stage = null;
}
function onChange(e:LocationChangeEvent):void {
trace(webView.location);
if(webView.location.indexOf("http://google.com") == 0 && webView.location.indexOf("access_token")!=-1) {
trace("?"+webView.location.substring(webView.location.indexOf("access_token"), webView.location.indexOf("&expires_in")));
webView.stage = null;
}
}
function connectFb() {
webView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, onChanging);
webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, onChange);
webView.stage = stage;
webView.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
webView.loadURL("https://graph.facebook.com/oauth/authorize?client_id=123456789012345&redirect_uri=http://google.com&type=user_agent&display=popup")
}
My Codes output:
https://graph.facebook.com/oauth/authorize?client_id=164534120383085&redirect_uri=http://google.com&type=user_agent&display=popup
https://www.facebook.com/dialog/oauth?client_id=164534120383085&redirect_uri=http%3A%2F%2Fgoogle.com&type=user_agent&display=popup
https://www.facebook.com/dialog/oauth?client_id=164534120383085&redirect_uri=http%3A%2F%2Fgoogle.com&type=user_agent&display=popup
http://google.com/
http://google.com/
http://www.google.com/
http://www.google.com/
I tried every tutorial on the net and even bought a book on AS3 facebook dev & still cant figure this out; Any help would be VERY appreciated since this is a fairly important project to me
Use this where you are Updating UI example Loading Profile photo or Name of User
String acc = session.getAccessToken();
Log.e("Access-Token", acc);
Best of Luck

Categories

Resources