facebook login and share dialog not shown in android mobile in unity - facebook

I'm using facebook sdk 7.4 and unity 5.2.2f1 and I want to login into facebook profile and share the game using FB.FeedShare function in android phone. The login works in editor, but not in android phone. when login button is pressed, a dialog window is getting load but it disappears quickly. The share functionality has the same problem.
I'm stucked in this problem for 2 weeks, and I don't know what to do! I'll be so gratefull if anybody can solve it..
public void initFB() {
if (!FB.IsInitialized) {
FB.Init (setInit, onUnityHide);
} else {
isLoggedIn = FB.IsLoggedIn;
}
}
public void setInit() {
if (FB.IsLoggedIn) {
Debug.Log ("u r logged in!");
getProfile();
} else {
Debug.Log ("u r not logged in!");
}
isLoggedIn = FB.IsLoggedIn;
}
private void onUnityHide(bool isShown) {
if (!isShown) {
Time.timeScale = 0;
} else {
Time.timeScale = 1;
}
}
public void FBLogin() {
List<string> perms = new List<string> ();
perms.Add ("public_profile");
FB.LogInWithReadPermissions (perms, authCallBack);
}
public void authCallBack(IResult result) {
if (result.Error != null) {
Debug.Log (result.Error.ToString ());
} else {
if (FB.IsLoggedIn) {
FacebookManager.Instance.isLoggedIn = true;
FacebookManager.Instance.getProfile();
Debug.Log ("you are logged in!");
} else {
Debug.Log ("you are not logged in!");
}
setMenu(FB.IsLoggedIn);
}
}
public void share() {
FB.FeedShare (
string.Empty,
null,
"Hi Title!",
"Hi Caption!",
"Hi Description!",
new System.Uri("http://s3.img7.ir/hPyQA.jpg"),
string.Empty,
shareCall
);
}
public void shareCall(IResult result) {
if (result.Cancelled) {
Debug.Log ("share cancelled!");
} else if (!string.IsNullOrEmpty (result.Error)) {
Debug.Log ("error on share!");
} else if (!string.IsNullOrEmpty (result.RawResult)){
Debug.Log ("success on share!");
}
}

Related

DeveloperError Exception of type 'Google.GoogleSignIn+SignInException', googleplaystore, unity, google login?

I have weird behaviour for my SignInWithGoogle.
I have everything set up for QAuth, SSH, WebClieng etc.
And when I sent a build to my phone directly. All work fine. I can SignIn, LogIn etc.
But when I made an aab build and uploaded it to google console and downloaded it from GooglePlay, as a tester, I received DeveloperError Exception of type 'Google.GoogleSignIn+SignInException.
Is there maybe something I need to change on QAuth to fix that?
public class SignInWithGoogle : MonoBehaviour
{
public static string slaveUserEmail;
public static string slaveUserPassword;
string webClientId = "536446807232-vh3olku8c637olltqlge92p17qmsqmtl.apps.googleusercontent.com";
private GoogleSignInConfiguration configuration;
FirebaseAuth _auth;
bool _initialized = false;
void Awake()
{
FireBaseInit.OnInitialized += OnFirebaseInit;
configuration = new GoogleSignInConfiguration
{
WebClientId = webClientId,
RequestIdToken = true
};
}
public void OnFirebaseInit()
{
if (_initialized) return;
_auth = FirebaseAuth.DefaultInstance;
_initialized = true;
Debug.Log("GoogleAuth Initialized");
}
public void OnSignIn()
{
Debug.Log("Calling SignIn");
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
var signInCompleted = new TaskCompletionSource<FirebaseUser>();
Debug.Log("SignInInit");
try
{
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(task =>
{
if (task.IsFaulted)
{
using (IEnumerator<Exception> enumerator =
task.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
GoogleSignIn.SignInException error =
(GoogleSignIn.SignInException)enumerator.Current;
Debug.Log("Got Error: " + error.Status + " " + error.Message);
}
else
{
Debug.Log("Got Unexpected Exception?!?" + task.Exception);
}
}
}
else if (task.IsCanceled)
{
Debug.Log("Canceled");
}
else
{
Debug.Log("Welcome in Google: " + task.Result.DisplayName + "!");
Debug.Log("GEt Ceds");
Credential credential = GoogleAuthProvider.GetCredential(task.Result.IdToken, null);
Debug.Log("Creds added");
Debug.Log("Firebase Log In try!");
FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(credential).ContinueWith(authTask =>
{
if (authTask.IsCanceled)
{
Debug.Log("Auth Canceld");
signInCompleted.SetCanceled();
}
else if (authTask.IsFaulted)
{
Debug.Log("Auth Faulted");
signInCompleted.SetException(authTask.Exception);
}
else
{
Debug.Log("Auth Coplited");
signInCompleted.SetResult(((Task<FirebaseUser>)authTask).Result);
}
});
}
});
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
The full error:
Got Error: DeveloperError Exception of type 'Google.GoogleSignIn+SignInException' was thrown. <>c__DisplayClass8_0:b__0(Task`1) System.Threading.ThreadPoolWorkQueue:Dispatch()

Unity: Google Play Games crashes on login

I'm trying to save a variable using google play games cloud save. However it crashes when it signs in. I've definitely enabled it on the developer console. I never had this problem before I added the cloud save feature and it was just doing achievements and scoreboards. Also, when I'm not connected to the internet, it doesn't crash and locally saving the data works fine. Can any one help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.SavedGame;
using System.Text;
public class playgamesscript : MonoBehaviour {
public static playgamesscript Instance { get; private set; }
const string SAVE_NAME = "Test";
bool isSaving;
textEdit textEditScript;
control controlScript;
bool isCloudDataLoaded;
// Use this for initialization
void Start () {
Instance = this;
textEditScript = GameObject.FindGameObjectWithTag("UIControl").GetComponent<textEdit>();
controlScript = GameObject.FindGameObjectWithTag("Control").GetComponent<control>();
if (!PlayerPrefs.HasKey(SAVE_NAME))
PlayerPrefs.SetString(SAVE_NAME, "0");
if (!PlayerPrefs.HasKey("IsFirstTime"))
PlayerPrefs.SetInt("IsFirstTime", 1);
LoadLocal();
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().EnableSavedGames().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
if (control.signInAttempt == false)
{
SignIn();
}
}
void SignIn()
{
control.signInAttempt = true;
Social.localUser.Authenticate(success => { LoadData(); });
}
#region Saved Games
string GameDataToString()
{
return control.Highscore.ToString();
}
void StringToGameData(string cloudData, string localData)
{
if (PlayerPrefs.GetInt("IsFirstTime") == 1){
PlayerPrefs.SetInt("IsFirstTime", 0);
if (int.Parse(cloudData) > int.Parse(localData)){
PlayerPrefs.SetString(SAVE_NAME, cloudData);
}
}
else if (int.Parse(localData) > int.Parse(cloudData))
{
control.Highscore = int.Parse(localData);
AddScoreToLoeaderBoard(textEdit.leaderboardStat, control.Highscore);
isCloudDataLoaded = true;
SaveData();
return;
}
control.Highscore = int.Parse(cloudData);
isCloudDataLoaded = true;
}
void StringToGameData (string localData)
{
control.Highscore = int.Parse(localData);
}
void LoadData()
{
if (Social.localUser.authenticated)
{
isSaving = false;
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithManualConflictResolution(SAVE_NAME, DataSource.ReadCacheOrNetwork, true, ResolveConflict, OnSavedGameOpened);
}
else {
LoadLocal();
}
}
private void LoadLocal()
{
StringToGameData(PlayerPrefs.GetString(SAVE_NAME));
}
public void SaveData()
{
if (!isCloudDataLoaded)
{
SaveLocal();
return;
}
if (Social.localUser.authenticated)
{
isSaving = true;
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithManualConflictResolution(SAVE_NAME, DataSource.ReadCacheOrNetwork, true, ResolveConflict, OnSavedGameOpened);
}
else
{
SaveLocal();
}
}
private void SaveLocal()
{
PlayerPrefs.SetString(SAVE_NAME, GameDataToString());
}
private void ResolveConflict(IConflictResolver resolver, ISavedGameMetadata original, byte[] originalData, ISavedGameMetadata unmerged, byte[] unmergedData)
{
if (originalData == null)
{
resolver.ChooseMetadata(unmerged);
} else if (unmergedData == null)
{
resolver.ChooseMetadata(original);
} else
{
string originalStr = Encoding.ASCII.GetString(originalData);
string unmergedStr = Encoding.ASCII.GetString(unmergedData);
int originalNum = int.Parse(originalStr);
int unmergedNum = int.Parse(unmergedStr);
if (originalNum > unmergedNum)
{
resolver.ChooseMetadata(original);
return;
} else if (unmergedNum> originalNum)
{
resolver.ChooseMetadata(unmerged);
}
resolver.ChooseMetadata(original);
}
}
private void OnSavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game)
{
if (status == SavedGameRequestStatus.Success)
{
if (!isSaving)
{
LoadGame(game);
} else
{
SaveGame(game);
}
}
else
{
if (!isSaving)
{
LoadLocal();
}else
{
SaveLocal();
}
}
}
private void LoadGame(ISavedGameMetadata game)
{
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game, OnSavedGameDataRead);
}
private void SaveGame(ISavedGameMetadata game)
{
string stringToSave = GameDataToString();
PlayerPrefs.SetString(SAVE_NAME, stringToSave);
byte[] dataToSave = Encoding.ASCII.GetBytes(stringToSave);
SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game, update, dataToSave, OnSavedGameDataWritten);
}
private void OnSavedGameDataRead(SavedGameRequestStatus status, byte[] savedData)
{
if (status == SavedGameRequestStatus.Success)
{
string cloudDataString;
if (savedData.Length == 0)
{
cloudDataString = "0";
} else
cloudDataString = Encoding.ASCII.GetString(savedData);
string localDataString = PlayerPrefs.GetString(SAVE_NAME);
StringToGameData(cloudDataString, localDataString);
}
}
private void OnSavedGameDataWritten(SavedGameRequestStatus status, ISavedGameMetadata game)
{
}
#endregion /Saved Games
///
JNI DETECTED ERROR IN APPLICATION: can't call void com.google.android.gms.common.api.PendingResult.setResultCallback(com.google.android.gms.common.api.ResultCallback) on null object'

How to pass an anonymous function as parameter to onclick method C#

Using Unity 5.4 and FB SDK 7.9 I want to use the onclick button functionality to run the method Share. This method has many parameters, so I need to create the onclick functionality in code and not in the inspector. I am getting the error unexpected symbol link parameter expecting '.' What is going on? How can I fix this?
public class FBScript : MonoBehaviour {
public Button PostBtn;
void Start() {
Button btn = PostBtn.GetComponent<Button>();
btn.onClick.AddListener(delegate {
Share(string linkParameter, string namerParameter, string captionParameter, string descriptionParameter, string pictureParameter, string redirectParameter);
});
}
void Awake () {
FB.Init(SetInit, OnHideUnity);
}
void SetInit () {
if (FB.IsLoggedIn) {
Debug.Log("FB is Logged In");
} else {
Debug.Log("FB is not Logged In");
}
}
void OnHideUnity(bool isGameShown) {
if (!isGameShown) {
Time.timeScale = 0;
} else {
Time.timeScale = 1;
}
}
public void FBLogin() {
List<string> permissions = new List<string>();
permissions.Add("public_profile");
FB.LogInWithReadPermissions(permissions, AuthCallBack);
}
void AuthCallBack(ILoginResult result) {
if (result.Error != null) {
Debug.Log(result.Error);
} else {
if (FB.IsLoggedIn) {
Debug.Log("FB is Logged In");
} else {
Debug.Log("FB is not Logged In");
}
}
}
private const string FACEBOOK_APP_ID = "999999999999999";
private const string FACEBOOK_URL = "http://www.facebook.com/dialog/feed";
public void Share(string linkParameter, string namerParameter, string captionParameter, string descriptionParameter, string pictureParameter, string redirectParameter) {
Application.OpenURL(FACEBOOK_URL + "?app_id=" + FACEBOOK_APP_ID +
"&link=" + WWW.EscapeURL(linkParameter) +
"&name=" + WWW.EscapeURL(namerParameter) +
"&caption=" + WWW.EscapeURL(captionParameter) +
"&description=" + WWW.EscapeURL(descriptionParameter) +
"&picture=" + WWW.EscapeURL(pictureParameter) +
"&redirect_url=" + WWW.EscapeURL(redirectParameter));
}
}

Can't login with facebook in Windows Phone App

It was working fine before but It's not working even though I haven't changed anything in my Facebook related code. It is giving this error:
App doesn't give permission to given URL : The settings of app doesn't allow one or more of the given URL's. URLs must be Website's URL or Canvas URL...
Here is my FacebookLoginPage.cs:
namespace MyApp.Pages
{
public partial class FacebookLoginPage : PhoneApplicationPage
{
private string message;
public FacebookLoginPage()
{
InitializeComponent();
message = String.Empty;
this.Loaded += FacebookLoginPage_Loaded;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
NavigationService.GoBack();
base.OnBackKeyPress(e);
}
private async void FacebookLoginPage_Loaded(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(App.AccessToken))
{
App.isAuthenticated = true;
await Authenticate();
}
}
private FacebookSession session;
private async Task Authenticate()
{
//Facebook logini kontroli eğer login olduysa AccessToken ve bilgileri çeker.
try
{
if (App.FacebookSessionClient.LoginInProgress == true && !String.IsNullOrEmpty(message))
{
App.FacebookSessionClient.LoginInProgress = false;
}
else
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
App.AccessToken = session.AccessToken;
App.appSettings["accessToken"] = App.AccessToken;
App.appSettings.Save();
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/MainPage.xaml?token=" + App.AccessToken, UriKind.Relative)));
}
}
catch (InvalidOperationException)
{
message = "failed";
App.FacebookSessionClient.LoginInProgress = true;
NavigationService.GoBack();
}
}
}
}
What might be the probelm?
When I added facebook.com to Oauth part of Advanced Setting in my Facebook App, the problem solved. Thanks to the following link: Windows Phone 8 Facebook Login Given URL is not allowed by the application

Integrating Facebook into my Android app

I searched a lot for a perfect example of code that helps me understand how to integrate Facebook in my application. How can I integrate it?
please do the steps give in the below link
facebook android integration
You could use: http://code.google.com/p/facebook4j/
private static final String FB_KEY = "YOUR_KEY";
private Facebook facebook;
private String messageToPost;
facebook = new Facebook(FB_KEY);
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
public void loginAndPostToWall() {
facebook.authorize(activity, FB_PERMISSIONS,
Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
public void postToWall(String message) {
FBThread fbPost = new FBThread (message);
fbPost.start();
}
private class FBThread extends Thread {
String message;
FBThread(String message) {
this.message = message;
}
#Override
public void run() {
Bundle parameters = new Bundle();
parameters.putString("message", message);
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters,
"POST");
if (response == null || response.equals("")
|| response.equals("false")) {
toastMessage = "Blank response.";
} else if (response.contains("error")) {
toastMessage = "Post Failed because of duplicates...";
} else {
toastMessage = "Message posted to your facebook wall!";
}
} catch (Exception e) {
toastMessage = "Failed to post to wall!";
e.printStackTrace();
}
}
}
class LoginDialogListener implements DialogListener {
public void onCancel() {
android.webkit.CookieManager.getInstance().removeAllCookie();
}
public void onComplete(Bundle values) {
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onError(DialogError error) {
android.webkit.CookieManager.getInstance().removeAllCookie();
}
public void onFacebookError(FacebookError error) {
android.webkit.CookieManager.getInstance().removeAllCookie();
}
}