Login and Logout Users

Introduction

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.

To check if user is anonymous:

1
boolean anonymous = GetSocial.User.isAnonymous();
1
val anonymous = GetSocial.User.isAnonymous()
1
BOOL anonymous = [GetSocialUser isAnonymous];
1
let anonymous = GetSocialUser.isAnonymous
1
var anonymous = GetSocial.User.IsAnonymous;
1
2
3
GetSocial.User.isAnonymous().then((isAnonymous) => {
    console.log('User is anonymous? ' + isAnonymous);
});

Login

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.

Identities

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.

To create an identity:

1
2
3
4
5
// Create Facebook identity
AuthIdentity fbIdentity = AuthIdentity.createFacebookIdentity(fbAccessToken);

// Create Custom Identity
AuthIdentity customIdentity = AuthIdentity.createCustomIdentity(providerId, userId, accessToken);
1
2
3
4
5
// Create Facebook identity
val authIdentity = AuthIdentity.createFacebookIdentity(fbAccessToken)

// Create Custom Identity
val customUdentity = AuthIdentity.createCustomIdentity(providerId, userId, accessToken)
1
2
3
4
5
// Create Facebook identity
GetSocialAuthIdentity *fbIdentity = [GetSocialAuthIdentity facebookIdentityWithAccessToken:fbAccessToken];

// Create Custom Identity
GetSocialAuthIdentity *customIdentity = [GetSocialAuthIdentity customIdentityForProvider:providerId userId:userId accessToken:accessToken];
1
2
3
4
5
// Create Facebook identity
let fbIdentity = GetSocialAuthIdentity.facebookIdentityWithAccessToken(fbAccessToken)

// Create Custom Identity
let customIdentity = GetSocialAuthIdentity.customIdentityForProvider(providerId, userId:userId, accessToken:accessToken)
1
2
3
4
5
// Create Facebook identity
var fbIdentity = AuthIdentity.CreateFacebookIdentity(fbAccessToken);

// Create Custom Identity
var customIdentity = AuthIdentity.CreateCustomIdentity(providerId, userId, accessToken);
1
2
3
4
5
// Create Facebook identity
const fbIdentity = AuthIdentity.createFacebookIdentity(fbAccessToken);

// Create custom identity
const customIdentity = AuthIdentity.createCustomIdentity(providerId, userId, accessToken);
  • providerId is a unique string defined by you for each provider (twitter, my_auth_system, gamecenter, etc).
  • userId is a unique string 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.

Add Identity

You have to add an identity to GetSocial user in the success callback of your authentication system.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public void onLoginSuccess() {
    String userId = getCurrentUserId(); // get user ID on your login provider
    String accessToken = calculateAccessTokenForUser(userId); // see the example of such a function below
    final AuthIdentity identity = AuthIdentity.createCustomIdentity("my_auth_system", userId, accessToken);

    GetSocial.User.addAuthIdentity(identity, new AddAuthIdentityCallback() {
            @Override
            public void onComplete() {
                Log.d("GETSOCIAL", "Successfully logged into " + userId);
            }

            @Override
            public void onFailure(GetSocialException exception) {
                Log.d("GETSOCIAL", "Failed to log into " + userId + ", exception: " + exception.getMessage());
            }

            @Override
            public void onConflict(ConflictUser conflictUser) {
                handleConflict(identity, conflictUser);
            }
        })
}

// it should be always the same for the same value, so hashCode method perfectly fits to this job, but you can introduce something more advanced
public static String calculateAccessTokenForUser(String userId) {
    return String.valueOf(userId.hashCode());
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fun onLoginSuccess() {
    val userId = getCurrentUserId() // get user ID on your login provider
    val accessToken = calculateAccessTokenForUser(userId) // see the example of such a function below

    val identity = AuthIdentity.createCustomIdentity("my_auth_system", userId, accessToken)

    GetSocial.User.addAuthIdentity(identity, object : AddAuthIdentityCallback {
        override fun onComplete() {
            println("Successfully logged into ${userId}")
        }

        override fun onFailure(exception: GetSocialException) {
            println("Failed to log into ${userId}, error: ${exception.message}")
        }

        override fun onConflict(conflictUser: ConflictUser) {
            handleConflict(identity, conflictUser)
        }
    })
}

// it should be always the same for the same value, so hashCode method perfectly fits to this job, but you can introduce something more advanced
fun calculateAccessTokenForUser(userId: String): String {
    return "${userId.hashCode()}"
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
- (void)onLoginSuccess {
    NSString *userId = [self getCurrentUserId]; // get user ID on your login provider
    NSString *accessToken = [self calculateAccessTokenForUser:userId]; // see the example of such a function below
    GetSocialAuthIdentity *identity = [GetSocialAuthIdentity customIdentityForProvider:@"my_auth_system" userId:userId accessToken:accessToken];

    [GetSocialUser addAuthIdentity:identity
        success:^{
            NSLog(@"Successfully logged into %@", userId);
        }
        conflict:^(GetSocialConflictUser *conflictUser) {
            [self handleConflictForIdentity:identity conflictUser:conflictUser];
        }
        failure:^(NSError *error) {
            NSLog(@"Failed to log into %@", userId);
        }];
}

// it should be always the same for the same value, so hash method perfectly fits to this job, but you can introduce something more advanced
- (NSString *)calculateAccessTokenForUser:(NSString *)userId {
    return [NSString stringWithFormat:@"%lu", (unsigned long) userId.hash];
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func onLoginSuccess() {
    let userId = getCurrentUserId() // get user ID on your login provider
    let accessToken = calculateAccessToken(forUser: userId) // see the example of such a function below
    let identity = GetSocialAuthIdentity.customIdentity(forProvider: "my_auth_system", userId: userId, accessToken: accessToken)
    GetSocialUser.addAuthIdentity(identity, success: {
        print("Successfully logged into \(userId)")
    }, conflict: { conflictUser in
        self.handleConflict(forIdentity: identity, conflictUser: conflictUser)
    }, failure: { error in
        print("Failed to log into \(userId)")
    })
}

// it should be always the same for the same value, so hash method perfectly fits to this job, but you can introduce something more advanced
func calculateAccessToken(forUser userId: String) -> String {
    return "\(UInt(userId.hash))"
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public void OnLoginSuccess() {
    string userId = GetCurrentUserId(); // get user ID on your login provider
    string accessToken = CalculateAccessTokenForUser(userId); // see the example of such a function below
    AuthIdentity identity = AuthIdentity.CreateCustomIdentity("my_auth_system", userId, accessToken);

    GetSocial.User.AddAuthIdentity(identity,
            () =>
            {
                Debug.Log("Successfully logged into user " + userId);
            },
            error =>
            {
                Debug.Log("Failed to log into user " + userId + ", error:" + error);
            },
            conflictUser =>
            {
                HandleConflict(identity, conflictUser);
            });
}

// it should be always the same for the same value, so GetHashCode method perfectly fits to this job, but you can introduce something more advanced
public static string CalculateAccessTokenForUser(string userId) {
    return userId.GetHashCode().ToString();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
void onLoginSuccess = async() => {
    const userId = getCurrentUserId(); // get user ID on your login provider
    const accessToken = calculateAccessTokenForUser(userId); // see the example of such a function below
    const authIdentity = AuthIdentity.createCustomIdentity('my_auth_system', userId, accessToken);

    GetSocialUser.addAuthIdentity(authIdentity, () => {
        console.log("Successfully logged into user " + userId);
    }, (conflictUser) => {
        this.handleConflict(identity, conflictUser);
    }, (error) => {
        console.log("Failed to log into user " + userId + ", error:" + error);
    });
}

// example to generate hash code from userId, you can introduce something more advanced
calculateAccessTokenForUser(userId) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
    }
    return hash;
}

Add Facebook Identity

To add Facebook identity, you should provide the token you got from Facebook SDK after user’s authentication.

  1. Integrate Facebook SDK into your app as described in the Official Guide for iOS, Android or Unity.

  2. Add Facebook identity to GetSocial user. Sample code is below:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    final AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
            stopTracking(); // stop tracking facebook access token changes as we don't need it anymore
    
            AuthIdentity authIdentity = AuthIdentity.createFacebookIdentity(newAccessToken.getToken());
            GetSocial.User.addAuthIdentity(authIdentity, completionCallback);
        }
    };
    accessTokenTracker.startTracking();
    
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("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
    val accessTokenTracker = object: AccessTokenTracker() {
        override fun onCurrentAccessTokenChanged(oldAccessToken: AccessToken, currentAccessToken: AccessToken) {
            stopTracking() // stop tracking facebook access token changes as we don't need it anymore
    
            val authIdentity = AuthIdentity.createFacebookIdentity(currentAccessToken.token)
            GetSocial.User.addAuthIdentity(authIdentity, completionCallback)
        }
    }
    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
    18
    19
    20
    21
    22
    23
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    login.loginBehavior = FBSDKLoginBehaviorBrowser;
    
    [login
        logInWithReadPermissions:@[@"email", @"user_friends"] // we need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph
        fromViewController:self
        handler:^(FBSDKLoginManagerLoginResult *result, NSError *loginError) {
        if (!loginError && !result.isCancelled)
        {
            GetSocialAuthIdentity *identity = [GetSocialAuthIdentity facebookIdentityWithAccessToken:result.token.tokenString];
    
            [GetSocialUser addAuthIdentity:identity
                success:^{
                    NSLog(@"Successfully logged into FB");
                }
                conflict:^(GetSocialConflictUser *conflictUser) {
                    [self handleConflictForIdentity:identity conflictUser:conflictUser];
                }
                failure:^(NSError *error) {
                    NSLog(@"Failed to log into FB");
                }];
        }
    }];
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    let login = 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, loginError in
        if loginError == nil && result?.isCancelled == nil {
            let identity = GetSocialAuthIdentity.facebookIdentity(withAccessToken: result?.token.tokenString)
    
            GetSocialUser.add(identity, success: {
                print("Successfully logged into FB")
            }, conflict: { conflictUser in
                self.handleConflict(for: identity, conflictUser: conflictUser)
            }, failure: { error in
                print("Failed to log into FB")
            })
        }
    })
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    FB.Init(() => {
        var permissions = new List<string>(){"public_profile", "user_friends"}; // We need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph
        FB.LogInWithReadPermissions(permissions, result => {
            if (FB.IsLoggedIn) {
                var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
                var authIdentity = AuthIdentity.CreateFacebookIdentity(aToken.TokenString);
                GetSocial.User.AddAuthIdentity (authIdentity, OnSuccess, OnError, OnConflict);
            } else {
                Debug.Log("User cancelled login");
            }
        });
    });
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    // We need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph
    LoginManager.logInWithReadPermissions(['email', 'user_friends', 'public_profile']).then((result) => {
        if (result.isCancelled) {
            console.log('FB Login cancelled');
        } else {
            AccessToken.getCurrentAccessToken().then((token) => {
                if (token != null) {
                    const fbIdentity = AuthIdentity.createFacebookIdentity(token.accessToken);
                    GetSocial.User.AddAuthIdentity (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.

Handle Conflicts

Besides success and failure callbacks, addAuthIdentity 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
public void handleConflict(AuthIdentity identity, ConflicUser 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
fun handleConflict(identity: AuthIdentity, 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
- (void)handleConflictForIdentity:(GetSocialAuthIdentity *)identity conflictUser:(GetSocialConflictUser *)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
func handleConflict(for identity: GetSocialAuthIdentity, conflictUser: GetSocialConflictUser) {
    // 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
void HandleConflict(AuthIdentity 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
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
public void handleConflict(AuthIdentity identity, ConflicUser 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.User.switchUser(identity, completionCallback);
}
1
2
3
4
5
6
fun handleConflict(identity: AuthIdentity, 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.User.switchUser(identity, completionCallback)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
- (void)handleConflictForIdentity:(GetSocialAuthIdentity *)identity conflictUser:(GetSocialConflictUser *)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.
    [GetSocialUser switchUser:identity
        success:^{
            NSLog(@"Successfully switched user");
        }
        failure:^(NSError *error) {
            NSLog(@"Failed to switch user");
        }];];
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func handleConflict(for identity: GetSocialAuthIdentity, conflictUser: GetSocialConflictUser) {
    // 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.
    GetSocialUser.switch(identity, success: {
        print("Successfully switched user")
    }, failure: { error in
        print("Failed to switch user")
    })
}
1
2
3
4
5
6
7
void HandleConflict(AuthIdentity 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.User.SwitchUser(identity, completionCallback);
}
1
2
3
4
5
6
handleConflict(authIdentity, 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.
    GetSocialUser.switchUser(authIdentity);
}

Logout

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
public void onLogoutSuccess() {
    // New anonymous will be created. If your current user is anonymous - it will be lost.
    GetSocial.User.reset(completionCallback);
}
1
2
3
4
fun onLogoutSuccess() {
    // New anonymous will be created. If your current user is anonymous - it will be lost.
    GetSocial.User.reset(completionCallback)
}
1
2
3
4
- (void)onLogoutSuccess {
    // New anonymous user will be created. If your current user is anonymous - it will be lost.
    [GetSocialUser resetWithSuccess:success failure:failure];
}
1
2
3
4
func onLogoutSuccess() {
    // New anonymous user will be created. If your current user is anonymous - it will be lost.
    GetSocialUser.reset(success: success, failure: failure)
}
1
2
3
4
5
void OnLogoutSuccess()
{
    // New anonymous will be created. If your current user is anonymous - it will be lost.
    GetSocial.User.reset(OnSuccess, OnError);
}
1
2
3
4
onLogoutSuccess() {
    // New anonymous will be created. If your current user is anonymous - it will be lost.
    GetSocialUser.reset();
}

Subscribe to GetSocial user changes to be notified about logout events too.

Handle Multiple User Identities

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
 9
10
11
12
String providerId = "my_auth_system";
GetSocial.User.removeAuthIdentity(providerId, new CompletionCallback() {
    @Override
    public void onSuccess() {
        Log.d("GETSOCIAL", "Identity successfully removed.");
    }

    @Override
    public void onFailure(GetSocialException e) {
        Log.d("GETSOCIAL", "Failed, while removing identity.");
    }
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
val providerId = "my_auth_system"
GetSocial.User.removeAuthIdentity(providerId, object : CompletionCallback{
    override fun onSuccess() {
        println("Identity successfully removed.")
    }

    override fun onFailure(exception: GetSocialException) {
        println("Failed to remove identity, error: ${exception.message}")
    }
})
1
2
NSString *providerId = "my_auth_system";
[GetSocialUser removeAuthIdentityWithProviderId:providerId success:success failure:failure];
1
2
let providerId = "my_auth_system"
GetSocialUser.removeAuthIdentity(withProviderId: providerId, success: success, failure: failure)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
string providerId = "my_auth_system";
GetSocial.User.RemoveAuthIdentity(providerId,
    () =>
    {
        Debug.Log("Successfully remove identity");
    },
    error =>
    {
        Debug.Log("Failed remove identity, error:" + error);
    });
1
2
3
4
5
6
const providerId = 'my_auth_system';
GetSocialUser.removeAuthIdentity(providerId).then(() => {
    console.log('Successfully remove identity');
}, (error) => {
    console.log('Failed remove identity, error:' + error);
});

To get all user identities:

1
Map<String, String> identities = GetSocial.User.getAuthIdentities();
1
val identities = GetSocial.User.getAuthIdentities()
1
NSDictionary *identities = [GetSocialUser authIdentities];
1
let identities = GetSocialUser.authIdentities
1
var identities = GetSocial.User.AuthIdentities;
1
GetSocialUser.getAuthIdentities().then((authIdentities) => {});

where key is providerId and value is userId for that provider.

Change Logged In User

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.

Subscribe to User Lifecycle Changes

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
20
21
22
public class MainActivity extends Activity implements OnUserChangedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Setup GetSocial
        GetSocial.User.setOnUserChangedListener(this);

        ...
    }

    @Override
    public void onUserChanged() {
        Log.d(TAG, "Is SDK initialized?        " + GetSocial.isInitialized());
        Log.d(TAG, "Is user anonymous?         " + GetSocial.User.isAnonymous());
        Log.d(TAG, "What's user's avatar?      " + GetSocial.User.getAvatarUrl());
        Log.d(TAG, "What's user's name?        " + GetSocial.User.getDisplayName());
        Log.d(TAG, "List of user's identities: " + GetSocial.User.getAuthIdentities());
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class MainActivity : AppCompatActivity(), OnUserChangedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Setup GetSocial
        GetSocial.User.setOnUserChangedListener(this)

        ...
    }

    override fun onUserChanged() {
        println("Is SDK initialized? ${GetSocial.isInitialized()}")
        println("Is user anonymous? ${GetSocial.User.isAnonymous()}")
        println("What's user's avatar? ${GetSocial.User.getAvatarUrl()}")
        println("What's user's name? ${GetSocial.User.getDisplayName()}")
        println("List of user's identities: ${GetSocial.User.getAuthIdentities()}")
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@implementation MainViewController
...
- (void)viewDidLoad {
    [super viewDidLoad];
    ...
    [GetSocialUser setOnUserChangedHandler:^() {
        NSLog(@"User is anonymous: %@", GetSocialUser.isAnonymous ? @"Yes" : @"No");
        NSLog(@"User's displayName: %@", GetSocialUser.displayName);
        NSLog(@"User's avatarURL: %@", GetSocialUser.avatarUrl);
        NSLog(@"User's identites: %@", GetSocialUser.authIdentities);
    }];
    ...
}
...
@end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class ViewController: UIViewController {
    ...
    func viewDidLoad() {
        super.viewDidLoad()
        ...
        GetSocialUser.setOnUserChangedHandler {
            print("User is anonymous: \(GetSocialUser.isAnonymous ? "Yes" : "No")")
            print("User's displayName: \(GetSocialUser.displayName)")
            print("User's avatarURL: \(GetSocialUser.avatarUrl)")
            print("User's identites: \(GetSocialUser.authIdentities)")
        }
        ...
    }
}
1
2
3
4
5
6
7
8
9
void Awake()
{
    GetSocial.User.SetOnUserChangedListener(() => {
        Debug.Log ("User is anonymous:  " + GetSocial.User.IsAnonymous);
        Debug.Log ("User's displayName: " + GetSocial.User.DisplayName);
        Debug.Log ("User's avatarURL:   " + GetSocial.User.AvatarUrl);
        Debug.Log ("User's identites:   " + GetSocial.User.AuthIdentities);
    });
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
componentWillMount() {
    // Listen for events to set the proper information
    GetSocialUser.onUserChanged(() => {
        GetSocialUser.isAnonymous().then((isAnonymous) => {
            console.log('User is anonymous: ' + isAnonymous);
        });
        GetSocialUser.getDisplayName().then((displayName) => {
            console.log('Users display name: ' + displayName);
        });
        GetSocialUser.getAvatarUrl().then((avatarUrl) => {
            console.log('Users avatar url: ' + avatarUrl);
        });
        GetSocialUser.getAuthIdentities().then((authIdentities) => {
            console.log('Users identities: ' + JSON.stringify(authIdentities));
        });
    });
}

Next Steps

Well-done! Your user is set up, see what to do next:

Give us your feedback! Was this article helpful?

πŸ˜€ πŸ™