FB.Api error on unity - unity3d

I got error to get facebook name on Unity 3D, this function clearly working 2 weeks ago,
FB.Init(this.InitCallback, this.OnHideUnity);
private void InitCallback ()
{
if (FB.IsInitialized) {
if (FB.IsLoggedIn) {
FB.LogInWithReadPermissions(new List<string>() { "public_profile","email" }, this.AuthCallback);
} else {
}
} else {
Debug.Log("Failed to Initialize the Facebook SDK");
}
}
private void AuthCallback (ILoginResult result) {
if (FB.IsLoggedIn) {
FB.API("/me?fields=name", HttpMethod.GET, this.LoginCallback2);
} else {
//Debug.Log("User cancelled login");
}
}
void LoginCallback2(IResult result)
{
if (result.Error != null) {
Debug.Log(result.Error);
}
else{
fbid = result.ResultDictionary ["id"].ToString();
}
}
I got error on LoginCallback2 function, debug as follow:
UnityEngine.Debug:Log(Object)
connect:LoginCallback2(IResult) (at Assets/connect.cs:983)
Facebook.Unity.<Start>d__9:MoveNext()
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

The short answer is that either FB hasn't been initialized, or the user is NOT logged in. Below I have shared my own code for retrieving the User's full name and their FBID. You will want to check to make sure that the following is true before calling this code section:
FB.IsInitialized == true
and
FB.IsLoggedIn == true
if (result != null) {
if (string.IsNullOrEmpty(result.Error)) {
if (result.ResultDictionary != null)
if (result.ResultDictionary.ContainsKey("name")) {
result.ResultDictionary.TryGetValue("name", out Name);
}
if (result.ResultDictionary != null)
if (result.ResultDictionary.ContainsKey("id")) {
result.ResultDictionary.TryGetValue("id", out FBID);
}
}
}

Related

addEventListener on AppNavItem

I am using latest version of Vaadin.
Intended: want to catch an event if AppNavItem (with child elements) is clicked (expanded, toggled).
Code:
#JsModule("#vaadin-component-factory/vcf-nav")
#Tag("vcf-nav-item")
public class AppNavItem extends Component {
public AppNavItem(String label) {
setLabel(label);
}
public AppNavItem setExpanded(boolean value) {
if (value) {
getElement().setAttribute("expanded", "");
} else {
getElement().removeAttribute("expanded");
}
return this;
}
public AppNavItem setIcon(Component icon) {
icon.getElement().setAttribute("slot", "prefix");
int iconElementIndex = getIconElementIndex();
if (iconElementIndex != -1) {
getElement().setChild(iconElementIndex, icon.getElement());
} else {
getElement().appendChild(icon.getElement());
}
return this;
}
}
AppNavItem myItem = new AppNavItem("Project");
myItem.addAttachListener(e -> {
System.out.println(e.toString()); // works on page load as expected !
});
//projectParent.onEnabledStateChanged(false); // does not work
//projectParent.onEnabledStateChanged(true); // does not work
myItem.getElement().addEventListener("onchange", e -> {
System.out.println(e.getType()); // does not work
});
myItem.getElement().addPropertyChangeListener("expanded","onchange", e -> {
System.out.println(e.getPropertyName()); // does not work
});
myItem.getElement().addEventListener("onchange", e -> {
System.out.println(e.getType());
});
myItem.getElement().addPropertyChangeListener("expanded","onchange", e -> {
System.out.println(e.getPropertyName()); // does not work
});
myItem.getElement().addPropertyChangeListener("expanded", e -> {
System.out.println(e.getPropertyName()); // does not work
});
myItem.addItem(...);
I tried several eventTypes like: click, onclick, change, onchange, ontoggle, ...
Unfortunately, almost nothing works, see comment.
What am I doing wrong ?
I expect to catch an event

Facebook provider is not authenticating users in my ionic app - using angularfire

I am trying to implement (social & email-password) login in my ionic app..
It was working well for email-pass. When i tried adding google and facebook, i have faced a lot of problems, then a very dirty code. Now my code is working for googleauthentication, but for facebook, the app is redirecting, but returned result is {user: null}, and no thing changes.
What is the error? Why facebook authentication is not changing this.afAuth.authState?
Functionality is implemented in my auth.service.ts file.
A function for Facebook login is as so:
loginWithFacebook() {
this.store.dispatch(new UIActions.StartLoading());
alert('facebook login');
try {
let provider = new auth.FacebookAuthProvider();
console.log(provider);
const credential = this.afAuth.auth.signInWithRedirect(provider);
console.log('accomplished sign in with redirect');
} catch (error) {
console.log(error);
alert(error);
}
}
LoginWithGoogle (working as expected):
webGoogleLogin() {
try {
const provider = new firebase.auth.GoogleAuthProvider();
console.log(provider);
const credential = this.afAuth.auth.signInWithRedirect(provider);
console.log('accomplished sign in with redirect');
} catch (error) {
console.log(error);
alert(error);
}
}
I listen to auth changes in initAthListener(), which is fired on app initialization (it worked as expected for email-pass login - logout):
initAuthListener() {
// this.store.dispatch(new UIActions.StartLoading());
this.afAuth.authState.subscribe(user => {
// if( user && !user.emailVerified) {
// this.store.dispatch(new UIActions.StopLoading());
// this.alertService.presentToast(this.translateService.instant("Auth.PLEASE_VALIDATE_YOUR_EMAIL_ADDRESS"), 3000);
// }
console.log(user);
alert(user);
if (user) {
if(user.emailVerified) {
this.isAuthenticated = true;
this.store.dispatch(new AuthActions.SetAuthenticated());
this.afStore.collection('profiles').doc<FullUserProfile>(user.uid).valueChanges().pipe(take(1)).subscribe(
(profile: FullUserProfile) => {
if (profile != null) {
this.store.dispatch(new AuthActions.SetUserProfile(profile));
// this.functionsGeneralDataService.initialize(profile);
this.generalDataService.initialize(profile);
this.store.dispatch(new UIActions.StopLoading());
// this.router.navigate(['/groups']);
this.goToMainPage();
} else {
return;
}
}
);
}
} else {
this.isAuthenticated = false;
this.generalDataService.unsubscribeFromAll();
this.store.dispatch(new AuthActions.SetUnauthenticated());
this.store.dispatch(new AuthActions.RemoveUserProfile());
this.store.dispatch(new GroupsActions.ClearState());
// this.router.navigate(['/login']);
}
this.store.dispatch(new UIActions.StopLoading());
});
// this.listenToRedirectResults();
}
I have tried adding the following functionality at the end of inmitAuthListener(), but without solving the problem:
listenToRedirectResults() {
firebase.auth().getRedirectResult().then((result) => {
console.log(result);
console.log(firebase.auth().currentUser);
alert("THIS IS RESULT");
this.store.dispatch(new UIActions.StartLoading());
if (result.credential) {
alert('result.credentials is not null');
var token = result.user.getIdToken();
var user = result.user;
// if(result == null || result.user == null) {
// alert('result or user null');
// this.isAuthenticated = false;
// this.generalDataService.unsubscribeFromAll();
// this.store.dispatch(new AuthActions.SetUnauthenticated());
// this.store.dispatch(new AuthActions.RemoveUserProfile());
// this.store.dispatch(new GroupsActions.ClearState());
// }
alert('will get data');
this.store.dispatch(new AuthActions.SetAuthenticated());
this.afStore.collection('profiles').doc(user.uid).valueChanges().pipe(take(1)).subscribe(
(profile: FullUserProfile) => {
this.store.dispatch(new UIActions.StartLoading());
this.isAuthenticated = true;
if (profile != null) {
this.store.dispatch(new AuthActions.SetUserProfile(profile));
// this.functionsGeneralDataService.initialize(profile);
this.generalDataService.initialize(profile);
this.store.dispatch(new UIActions.StopLoading());
this.goToMainPage();
} else {
let profile = {} as FullUserProfile;
profile.id = user.uid;
profile.email = user.email;
profile.name = user.displayName;
profile.image = { name: '', url: user.photoURL}
profile.type = 0;
profile.numberOfGroupsAllowed = 2;
this.afStore.collection('profiles').doc(user.uid).set(profile);
this.store.dispatch(new AuthActions.SetUserProfile(profile));
// this.functionsGeneralDataService.initialize(profile);
this.generalDataService.initialize(profile);
this.store.dispatch(new UIActions.StopLoading());
this.goToMainPage();
// this.router.navigate(['/groups']);
}
}
);
// this.router.navigate(['groups'])
} else {
alert('no creadential');
}
})
.catch(function(error) {
console.log(error.message);
this.store.dispatch(new UIActions.StopLoading());
this.alertService.presentToast(error.message);
});
}
Notice: If the user is deleted from users of firebase console, and tried to sign in with facebook, then user is added there, but no changes in my app.
Sorry for my dirty code, i have cleaned a lot before asking the question..
Yesterday, before adding google authentication, facebook authentication was working, but logout was not.
Sorry, but i am new to the ionic framework.
The error: I am checking if email verified for a facebook account where email is not verified. I have restructured my code.

Phonegap AdMob does not work on iPhone

My problem is that admob plugin is not working on the PhoneGap IOS testing app (this is the plugin: https://github.com/appfeel/admob-google-cordova)
var isAppForeground = true;
function initAds() {
if (!admob) {
var adPublisherIds = {
ios : {
banner : "ca-app-pub-3940256099942544/2934735716",
interstitial : "ca-app-pub-3940256099942544/4411468910"
},
android : {
banner : "ca-app-pub-3940256099942544/6300978111",
interstitial : "ca-app-pub-3940256099942544/1033173712"
}
};
var admobid = (/(android)/i.test(navigator.userAgent)) ? adPublisherIds.android : adPublisherIds.ios;
admob.setOptions({
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
//tappxIdiOS: "/XXXXXXXXX/Pub-XXXX-iOS-IIII",
//tappxIdAndroid: "/XXXXXXXXX/Pub-XXXX-Android-AAAA",
//tappxShare: 0.5,
});
registerAdEvents();
} else {
alert('admobAds plugin not ready');
}
}
function onAdLoaded(e) {
if (isAppForeground) {
if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
console.log("An interstitial has been loaded and autoshown. If you want to load the interstitial first and show it later, set 'autoShowInterstitial: false' in admob.setOptions() and call 'admob.showInterstitialAd();' here");
} else if (e.adType === admob.AD_TYPE_BANNER) {
console.log("New banner received");
}
}
}
function onPause() {
if (isAppForeground) {
admob.destroyBannerView();
isAppForeground = false;
}
}
function onResume() {
if (!isAppForeground) {
setTimeout(admob.createBannerView, 1);
setTimeout(admob.requestInterstitialAd, 1);
isAppForeground = true;
}
}
// optional, in case respond to events
function registerAdEvents() {
document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
document.addEventListener(admob.events.onAdFailedToLoad, function (e) {});
document.addEventListener(admob.events.onAdOpened, function (e) {});
document.addEventListener(admob.events.onAdClosed, function (e) {});
document.addEventListener(admob.events.onAdLeftApplication, function (e) {});
document.addEventListener(admob.events.onInAppPurchaseRequested, function (e) {});
document.addEventListener("pause", onPause, false);
document.addEventListener("resume", onResume, false);
}
The plugin is successfully installed and I placed these 3 lines under onDeviceReady:
initAds();
admob.createBannerView();
admob.requestInterstitialAd();
Everything after the lines above, in the same function (onDeviceReady) is not executed (the function crashes).
Again, I use the PhoneGap app for testing (from AppStore).

How to sequentially execute a "Completable" followed by "Single"?

I have two reactive methods in "Layer A" that's exposed to the app:
LAYER A - publicly accessible methods to the rest of the app
public Single<ResponseData> postMyData(ReqData data, Long id) {
if (!isUserLoggedIn()) return postLogin().andThen(postData(data, id));
return postData(data, id);
}
public Completable postLogin() {
Account account = getAccountData();
ReqLoginData loginData = new ReqLoginData(account.email, account.pass, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET);
Single<ResponseLogin> singlePostLogin = postLogin(loginData);
return Completable.create(subscriber -> singlePostLogin.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(loginResponse -> {
// Success
storeAccessToken(loginResponse);// *** this will recreate apiClient with new access token
if (!subscriber.isDisposed()) subscriber.onComplete();
}, throwable -> { if (!subscriber.isDisposed()) subscriber.onError(throwable);}
));
}
LAYER B - only accessible by Layer A
public Single<ResponseLogin> postLogin(ReqLoginData loginData) {
Log.d(TAG, "using apiClient "+apiClient.toString());
Single<Response<ResponseLogin>> postLogin = apiClient.postLogin(loginData);
return Single.create(subscriber -> postLogin.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
}));
}
public Single<ResponseData> postData(ReqData data, Long id) {
Log.d(TAG, "using apiClient "+apiClient.toString());
Single<Response<ResponseData>> postData = apiClient.postData(id, data);
return Single.create(subscriber -> postData.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
}));
}
LAYER C - API Interface
#Headers({"Content-Type: application/json"})
#POST(Constants.API_PREFIX + "/auth/token/")
Single<Response<ResponseLogin>> postLogin(#Body ReqLoginData reqLoginData);
#Headers({"Content-Type: application/json"})
#POST(Constants.API_PREFIX + "/data/{id}/")
Single<Response<ResponseData>> postData(#Path("id") Long id, #Body ReqData reqData);
A huge challenge for me at the moment is to make sure the user is logged-in before attempting to POST data. So, using postLogin().andThen(postData(data, id)) made sense to me :
At the time of my late-night development, it seemed that both methods postLogin() and postData() are called in parallel - with postLogin() first.
How can I make postMyData() execute postLogin() first, wait for success or failure, followed by postData() on success ?
Note: postLogin() will update apiClient with the new token inside storeAccessToken(). I now see that postData() doesn't use a reference to the new apiClient. It's important that postData() will use the new apiClient that's instantiated within storeAccessToken()
Sorry for the newbie question :-(
it turned out that Completable.andThen(Single) works very well to serialize code execution. Unfortunately, I didn't (half asleep) realize that only code within the create() method was actually scheduled.
my code below answers the problem I had (these are both in LAYER-B):
public Single<ResponseLogin> postLogin(ReqLoginData loginData) {
return Single.create(subscriber -> {
Log.d(TAG, "using apiClient "+apiClient.toString());
apiClient.postLogin(loginData)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.isSuccessful() && response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
});
});
}
public Single<ResponseData> postData(ReqData data, Long id) {
return Single.create(subscriber -> {
Log.d(TAG, "using apiClient "+apiClient.toString());
apiClient.postData(id, data)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
});
});
}

form validation on submit

I am facing problem in form validation. Following is my jQuery validation code.
kindly help me how this validation is working on submit button.
<script type="text/javascript">
$(document).ready(function() {
$(".col a").click(function() {
$(".col a").removeClass("active");
$(this).addClass("active");
});
});
jQuery(document).ready(function() {
jQuery(".expContent").hide();
//toggle the componenet with class msg_body
jQuery(".expHeading").click(function() {
jQuery(this).next(".expContent").slideToggle(500);
});
});
$(document).ready(function() {
// Vertical
$("#vertical").on("blur", function(e) {
if ($("#vertical").val().length < 2) {
alert("vertical", "Vertical is Mandatory");
} else {
hideMsg("vertical");
}
});
// Name
$("#name").on("blur", function(e) {
if ($("#name").val().length < 2) {
alert("Name is Mandatory");
} else {
hideMsg("name");
}
});
function IsEmail(email) {
var filter = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/;
if (filter.test(email)) {
return true;
} else {
return false;
}
}
$("#email").on("blur", function(e) {
if ($("#email").val().length == 0) {
//alert("Please submit a Valid Email Id");
}
if (IsEmail($("#email").val())) {
hideMsg("email");
} else {
alert("Please submit a Valid Email Id");
}
});
// Mobile No
$("#enqMobileNo").on("blur", function(e) {
if ($("#enqCountryResidence").val() == "in") {
if ($("#enqMobileNo").val().length == 10) {
hideMsg("enqMobileNo");
} else {
alert('Please Enter 10 Digit Mobile No. Only like 9812345678. Without Area or Country Code i.e "0" or "+91"');
}
} else {
if ($("#enqMobileNo").val().length 1) {
hideMsg("enqMobileNo");
} else {
alert("Please Enter Mobile No. Only. Without Area or Country Code");
}
}
});
$("#enqMobileNo").on('keyup', function() {
if ($("#enqMobileNo").val() == "0") {
$("#enqMobileNo").val("");
}
if ($("#enqCountryResidence").val() == "in") {
limitText(this, 10);
if ($("#enqMobileNo").val().length == 10) {
hideMsg("enqMobileNo");
}
} else {
//inlineMsg
("enqMobileNo", "Please Enter Mobile No. Only<br /Without Area or Country Code");
}
});
// Gender
$("#gender").on("blur", function(e) {
if ($("#gender").val() == "") {
alert('Please select Gender', 2);
} else {
hideMsg("gender");
}
});
// Age
$("#age").on("blur", function(e) {
if ($("#age").val() == "") {
alert('Please select Age', 2);
} else {
hideMsg("age");
}
});
// City
$("#enqCity").on("blur", function(e) {
if ($("#enqCity").val() == "") {
alert('Current Location City Name is Mandatory', 2);
} else {
hideMsg("enqCity");
}
});
// Course
$("#enqSection").on("blur", function(e) {
if ($("#enqSection").val() == "") {
alert('Please Select Course', 2);
} else {
hideMsg("enqSection");
}
});
// Spl
$("#enqSpeciality").on("blur", function(e) {
if ($("#enqSpeciality").val() == "") {
alert('Please Select Speciality', 2);
} else {
hideMsg("enqSpeciality");
}
});
// Level
$("#enqLevel").on("blur", function(e) {
if ($("#enqLevel").val() == "") {
alert('Please Select Level', 2);
} else {
hideMsg("enqLevel");
}
});
function limitText(field, maxChar) {
var ref = $(field),
val = ref.val();
if (val.length = maxChar) {
ref.val(function() {
console.log(val.substr(0, maxChar))
return val.substr(0, maxChar);
});
}
}
});
</script>
I think it is better to use jQuery form validation plugin. It is very easy to use.You can get step by step help with examples on this site