If you have configured your application, you can start using GetSocial without any additional steps. GetSocial creates anonymous user by default, so you can access all the features right after SDK gets initialized.
Anonymous user is just a user, that has no identities added. User is created per device and stays there for next sessions. Anonymous users have default names like “User 12345678”, but you can easily change it.
If you have internal login system or use any social authentication, you should connect your account to GetSocial user, so you can retrieve the same GetSocial user from another devices or recover it once app was reinstalled or user was logged out.
To connect GetSocial user with yours, you should add your identity to GetSocial user.
An identity is some unique user data to identify them among other users. You can use any auth provider to create an identity (your custom login, facebook, twitter, google, github, etc). Each user may have any number of different identities, but only one of the same provider. It means that you may attach one facebook, one twitter and one custom identity, but you can not attach two facebook identities. Read more how to attach multiple identities.
providerId is a unique string defined by you for each provider (twitter, my_auth_system, gamecenter, etc).
userId is a unique UserId for each user in the provided authentication system. So pair providerId-userId is unique for each user and helps GetSocial identify a user if them try to login from another device.
accessToken is a string for security check, that could be some internal hash function in your app based on userId. If user is trying to authenticate again with the same providerId and userId, but different accessToken - GetSocial won’t allow to authenticate. accessToken can not be changed.
funonLoginSuccess(){valuserId=getCurrentUserId()// get user ID on your login providervalaccessToken=calculateAccessTokenForUser(userId)// see the example of such a function belowvalidentity=Identity.custom("my_auth_system",userId,accessToken)valcurrentUser=GetSocial.getCurrentUser()if(currentUser==null){// you can't add identity before SDK is initializedreturn}currentUser.addIdentity(identity,{Log.d("CurrentUser","Identity added successfully")},{conflictUser:ConflictUser->handleConflic(identity,conflictUser)},{error:GetSocialError->Log.d("CurrentUser","Failed to add identity: $error")})}funcalculateAccessTokenForUser(userId:String):String{return...// you should implement your function to be identical on all platforms}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
letuserId=getCurrentUserId()// get user ID on your login providerletaccessToken=calculateAccessToken(userId)// see the example of such a function belowletidentity=Identity.custom(providerId:"my_auth_system",userId:userId,accessToken:accessToken)GetSocial.currentUser()?.addIdentity(identity,success:{print("Successfully logged into \(userId)")},conflict:{conflictUserinself.handleConflict(identity:identity,conflictUser:conflictUser)},failure:{errorinprint("Failed to log into \(userId)")})funccalculateAccessToken(userId:String)->String{return...// you should implement your function to be identical on all platforms}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
varuserId=GetCurrentUserId();// get user ID on your login providervaraccessToken=CalculateAccessToken(userId);// generate access token. make sure token generation code returns the same result on every platform.varidentity=Identity.Custom("my_auth_system",userId,accessToken);GetSocial.GetCurrentUser().AddIdentity(identity,()=>{Debug.Log("Successfully logged into "+userId);},(conflictUser)=>{HandleConflict(conflictUser);},(error)=>{Debug.Log("Failed to log into "+userId);});stringCalculateAccessToken(stringuserId){return...// make sure token generation code returns the same result on every platform}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
varuserId=getCurrentUserId(); // get user ID on your login providervaraccessToken=calculateAccessToken(); // generate access token. make sure token generation code returns the same result on every platform.varidentity=Identity.custom('my_auth_system', userId, accessToken);varuser=awaitGetSocial.currentUser;user.addIdentity(identity,
()=> { print('Successfully logged into '+userId)},
(conflictUser)=> { handleConflict(conflictUser) },
(error)=> { print('Failed to log into '+userId)});
}
StringcalculateAccessToken(StringuserId) {
return ... //makesuretokengenerationcodereturnsthesameresultoneveryplatform
}
1
2
3
4
5
6
7
8
9
10
11
12
13
constuserId=getCurrentUserId();// get user ID on your login providerconstaccessToken=calculateAccessToken();// generate access token. make sure token generation code returns the same result on every platform.constidentity=Identity.createCustomIdentity('my_auth_system',userId,accessToken);constcurrentUser=awaitGetSocial.getCurrentUser();currentUser.addIdentity(identity,()=>{console.log('Successfully logged into '+userId);},(conflictUser)=>{handleConflict(conflictUser);},(error)=>{console.log('Failed to log into '+userId);});funccalculateAccessToken(StringuserId){return...// make sure token generation code returns the same result on every platform}
To add Facebook identity, you should provide the token you got from Facebook SDK after user’s authentication.
Integrate Facebook SDK into your app as described in the Official Guide for iOS, Android or Unity.
Add Facebook identity to GetSocial user. Sample code is below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
valaccessTokenTracker=object:AccessTokenTracker(){overridefunonCurrentAccessTokenChanged(oldAccessToken:AccessToken,currentAccessToken:AccessToken){stopTracking()// stop tracking facebook access token changes as we don't need it anymorevalcurrentUser=GetSocial.getCurrentUser()if(currentUser==null){// you can't add identity before SDK is initialized// you can save the token to use it lateraccessToken=currentAccessTokenreturn}currentUser.addIdentity(Identity.facebook(currentAccessToken),{},{},{})}}accessTokenTracker.startTracking()LoginManager.getInstance().logInWithReadPermissions(this@MainActivity,listOf("email","user_friends"))// we need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
letlogin=FBSDKLoginManager()login.loginBehavior=FBSDKLoginBehaviorBrowser/* we need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph */login.logIn(withReadPermissions:["email","user_friends"],fromViewController:self,handler:{result,loginErrorinifloginError==nil&&result?.isCancelled==nil{letidentity=Identity.facebook(accessToken:result?.token.tokenString)GetSocial.currentUser().addIdentity(identity,success:{print("Successfully logged into FB")},conflict:{conflictUserinself.handleConflict(for:identity,conflictUser:conflictUser)},failure:{errorinprint("Failed to log into FB")})}})
1
2
3
4
5
6
7
8
9
10
11
12
FB.Init(()=>{varpermissions=newList<string>(){"public_profile","user_friends"};// We need "user_friends" permission to import list of Facebook friends to GetSocial Social GraphFB.LogInWithReadPermissions(permissions,result=>{if(FB.IsLoggedIn){varaToken=Facebook.Unity.AccessToken.CurrentAccessToken;varidentity=Identity.Facebook(aToken.TokenString);GetSocial.GetCurrentUser().AddIdentity(identity,OnSuccess,OnError,OnConflict);}else{Debug.Log("User cancelled login");}});});
1
2
3
4
5
6
7
8
varfbIdentity=Identity.facebook(fbAcessToken);varuser=awaitGetSocial.currentUser;user.addIdentity(fbIdentity,()=>{print('Successfully logged into '+fbIdentity)},(conflictUser)=>{handleConflict(conflictUser)},(error)=>{print('Failed to log into '+fbIdentity)});}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// We need "user_friends" permission to import list of Facebook friends to GetSocial Social GraphLoginManager.logInWithReadPermissions(['email','user_friends','public_profile']).then((result)=>{if(result.isCancelled){console.log('FB Login cancelled');}else{AccessToken.getCurrentAccessToken().then((token)=>{if(token!=null){constfbIdentity=Identity.createFacebookIdentity(token.accessToken);constcurrentUser=awaitGetSocial.getCurrentUser();currentUser.addIdentity(authIdentity,()=>{},(conflictUser)=>{},(error)=>{});}});}},(error)=>{console.log('FB login failed with error: '+error);});
For Facebook, we will retrieve the list of Facebook friends and import them to Social Graph, so you can get list of user’s friends through GetSocial.
GetSocial doesn’t automatically sync your Facebook profile info
Donβt forget to sync the display name and avatar of the GetSocial user with the values from Facebook. You can do it with a batch update to make it in one call.
Besides success and failure callbacks, addIdentity has conflict. Conflict happens when identity you’re trying to add is already attached to one of GetSocial users. It may happen when:
User has already logged in on another device.
User reinstalled the application.
User cleared application data.
Depending on the user intention and your application logic, you can choose one of the following strategies to resolve the conflict.
Strategy 1: stay with current user and don’t add identity:
1
2
3
4
funhandleConflict(identity:Identity,conflictUser:ConflictUser){// Do nothing in onConflict and user will stay the same.// Identity won't be added to any of the users.}
1
2
3
4
funchandleConflict(identity:Identity,conflictUser:ConflictUser){// Do nothing in onConflict and user will stay the same.// Identity won't be added to any of the users.}
1
2
3
4
5
voidHandleConflict(Identityidentity,ConflictUserconflictUser){// Do nothing in onConflict and user will stay the same.// Identity won't be added to any of the users.}
1
2
3
4
handleConflict(Identityidentity, ConflictUserconflictUser) {
//DonothinginonConflictanduserwillstaythesame.
//Identitywon't be added to any of the users.
}
1
2
3
4
handleConflict(authIdentity,conflictUser){// Do nothing in onConflict and user will stay the same.// Identity won't be added to any of the users.}
Strategy 2: switch to conflict user:
1
2
3
4
5
6
funhandleConflict(identity:Identity,conflictUser:ConflictUser){// Call switchUser to replace current user with conflict one and add identity to conflict user.// After the successful switch, current user and his referral data will be lost. // To save the data: 1. copy data to intermediate variables; 2. save in to the conflict user properties after the successful switch. GetSocial.switchUser(identity,{/** onSuccess **/},{/** onError **/})}
1
2
3
4
5
6
7
8
9
10
funchandleConflict(identity:Identity,conflictUser:ConflictUser){// Call switchUser to replace current user with conflict one and add identity to conflict user.// After the successful switch, current user and his referral data will be lost.// To save the data: 1. copy data to intermediate variables; 2. save in to the conflict user properties after the successful switch.GetSocial.switchUser(to:identity,success:{print("Successfully switched user")},failure:{errorinprint("Failed to switch user")})}
1
2
3
4
5
6
7
voidHandleConflict(Identityidentity,ConflictUserconflictUser){// Call switchUser to replace current user with conflict one and add identity to conflict user.// After the successful switch, current user and his referral data will be lost. // To save the data: 1. copy data to intermediate variables; 2. save in to the conflict user properties after the successful switch.GetSocial.SwitchUser(identity,completionCallback);}
1
2
3
4
5
6
handleConflict(Identityidentity, ConflictUserconflictUser) {
//CallswitchUsertoreplacecurrentuserwithconflictoneandaddidentitytoconflictuser.
//Afterthesuccessfulswitch, currentuserandhisreferraldatawillbelost.
//Tosavethedata: 1. copydatatointermediatevariables; 2. save in to the conflict user properties after the successful switch.GetSocial.switchUser(identity).then(...);
}
1
2
3
4
5
6
handleConflict(identity,conflictUser){// Call switchUser to replace current user with conflict one and add identity to conflict user.// After the successful switch, current user and his referral data will be lost. // To save the data: 1. copy data to intermediate variables; 2. save in to the conflict user properties after the successful switch.GetSocial.switchUser(identity);}
If your users can log out of your app, you should log out of GetSocial user too. Otherwise it will stay the same and will have connection with another user that will login after.
1
2
3
4
funonLogoutSuccess(){// New anonymous will be created. If your current user is anonymous - it will be lost.GetSocial.resetUser({/** onSuccess **/,/** onError **/})}
1
2
3
4
funconLogoutSuccess(){// New anonymous user will be created. If your current user is anonymous - it will be lost.GetSocial.resetUser(success:successCallback,failure:failureCallback)}
1
2
3
4
5
voidOnLogoutSuccess(){// New anonymous will be created. If your current user is anonymous - it will be lost.GetSocial.ResetUser(OnSuccess,OnError);}
You may want to connect multiple identities (login with Facebook and Google at the same time). It will allow to log into that user with different auth providers.
Your user may have any number of different identities attached for different login providers, but only one identity for each provider.
You already know how to add identity. Once it is successfully added, you can log in using that identity.
To remove identity from user:
1
2
3
4
5
6
7
8
valproviderId="my_auth_system"valcurrentUser=GetSocial.getCurrentUser()if(currentUser==null){// you can't remove identity before SDK is initializedreturn}currentUser.removeIdentity(providerId,{/** onSuccess **/,/** onError **/})
varproviderId="my_auth_system";varcurrentUser=GetSocial.GetCurrentUser();if(currentUser==null){// you can't remove identity before SDK is initializedreturn}currentUser.RemoveIdentity(providerId,OnSuccess,OnError);
1
2
3
4
5
6
7
varproviderId="my_auth_system";varcurrentUser=awaitGetSocial.currentUser;if(currentUser==null) {
//youcan't remove identity before SDK is initializedreturn
}
currentUser.removeIdentity(providerId).then(...);
If you want to switch from one logged in user to another, do Logout first and then Login with a new user.
Warning
Don’t forget to do the logout, it is important to keep your user connected with proper GetSocial user, so you will receive correct analytics and referral data.
Set your custom event handler somewhere on the start of your application:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classMainActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)// Setup GetSocialvallistenerId=GetSocial.addOnCurrentUserChangedListener{newUser:CurrentUser->Log.d("CurrentUser","Is user anonymous? ${newUser.isAnonymous}")Log.d("CurrentUser","What's user's avatar? ${newUser.avatarUrl}")Log.d("CurrentUser","What's user's name? ${newUser.displayName}")Log.d("CurrentUser","List of user's identities: ${newUser.identities}")}...// You can remove the listener laterGetSocial.removeOnCurrentUserChangedListener(listenerId)}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classViewController:UIViewController{...funcviewDidLoad(){super.viewDidLoad()...letlistenerId=GetSocial.addOnCurrentUserChangedListener{currentUserinprint("User is anonymous: \(currentUser.isAnonymous?"Yes":"No")")print("User's displayName: \(currentUser.displayName)")print("User's avatarURL: \(currentUser.avatarUrl)")print("User's identites: \(currentUser.identities)")}...// You can remove the listener laterGetSocial.removeOnCurrentUserChangedListener(listenerId)}}
1
2
3
4
5
6
7
8
9
varlistenerId=GetSocial.AddOnCurrentUserChangedListener((currentUser)=>{Debug.Log("User is anonymous: "+currentUser.IsAnonymous);Debug.Log("User's displayName: "+currentUser.DisplayName);Debug.Log("User's avatarURL: "+currentUser.AvatarUrl);Debug.Log("User's identites: "+currentUser.Identities);});// You can remove the listener laterGetSocial.RemoveOnCurrentUserChangedListener(listenerId);
1
2
3
4
5
6
GetSocial.addOnCurrentUserChangedListener((currentUser)=>{print('User is anonymous: $currentUser.isAnonymous'),print('User displayName: $currentUser.displayName'),print('User avatarURL: $currentUser.avatarUrl'),print('User identites: $currentUser.identities'),});
1
2
3
4
5
6
GetSocial.addOnCurrentUserChangedListener((currentUser)=>{console.log('User is anonymous: '+currentUser.isAnonymous);console.log('User displayName: '+currentUser.displayName);console.log('User avatarURL: '+currentUser.avatarUrl);console.log('User identites: '+currentUser.identities);});