Skip to content

User Management

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 change it using [GetSocialUser setDisplayName:] method.

To check if user is anonymous use [GetSocialUser 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, use [GetSocialAuthIdentity facebookIdentityWithAccessToken:] for Facebook or [GetSocialAuthIdentity customIdentityForProvider:userId:accessToken:] for any other provider, where:

  • providerId is a unique NSString defined by you for each provider (twitter, my_auth_system, gamecenter, etc).
  • userId is a unique NSString 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 NSString 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
- (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))"
}

Add Facebook Identity

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

  1. Integrate Facebook iOS SDK into your app as described in the Official Guide.

  2. 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
    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")
            })
        }
    })
    

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 blocks, 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
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.
}

Strategy 2: switch to conflict user:

 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")
    })
}

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

If you’re subsribed to GetSocial user change then your OnUserChangedHandler will be invoked.

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.

Manage User Profile

Display Name

Check current username with [GetSocialUser displayName] method. To update display name use [GetSocialUser setDisplayName:newDisplayName success:success failure:failure].

Avatar

Get current avatar URL with [GetSocialUser avatarUrl] method. You can set a new avatar in two ways:

  • Set a URL - [GetSocialUser setAvatarUrl:avatarUrl success:success failure:failure].
  • Set a UIImage object - [GetSocialUser setAvatar:uiImageAvatar success:success failure:failure]. Recommended size is 300x300 px, bigger images will be automatically downscaled.

User Properties

Custom properties are NSString to NSString map of any information your want to store.

There’re some limitations about properties:

  • Max key length is 32 symbols.
  • Max value length is 1024 symbols.
  • Min value length is 1 symbol, you can not set an empty property, it will just remove a current value if it exists.

There are Public and Private properties. Private properties are accessible only by current user with methods listed in GetSocialUser.h class, Public can be accessed by other users with methods from GetSocialPublicUser.h object.

Private Properties

To set a private property:

1
2
3
4
5
6
7
8
[GetSocialUser setPrivatePropertyValue:value
                                forKey:key
                               success:^() {
                                   NSLog(@"Successfully set a private property");
                               }
                               failure:^(NSError *error) {
                                   NSLog(@"Failed to set a private property, error: %@", error.description);
                               }];
1
2
3
4
5
GetSocialUser.setPrivatePropertyValue(value, forKey: key, success: {
    print("Successfully set a private property")
}, failure: { error in
    print("Failed to set a private property, error: \(aDescription)")
})

In case if user already had a value for a current key, it will be overriden. You can prevent it with checking if property already exists:

1
BOOL hasPrivateProperty = [GetSocialUser hasPrivatePropertyForKey:key];
1
let hasPrivateProperty: Bool = GetSocialUser.hasPrivateProperty(forKey: key)

You can get the current property value:

1
NSString *currentValue = [GetSocialUser privatePropertyValueForKey:key];
1
let currentValue = GetSocialUser.privatePropertyValue(forKey: key)

If you’re not interesting in keeping property for a user, remove it:

1
[GetSocialUser removePrivatePropertyForKey:key success:success failure:failure];
1
GetSocialUser.removePrivateProperty(forKey: key, success: success, failure: failure)

You can get all properties as unmodifiable copy of origin map:

1
NSDictionary<NSString *, NSString *> *userProperties = [GetSocialUser allPrivateProperties];
1
let userProperties = GetSocialUser.allPrivateProperties()

Note

You can not modify properties with this map. Also, changes in user properties won’t affect your copy, so you need to refresh it after any user changes. To have up-to-date information, we suggest to use GetSocial SDK methods.

Public Properties

You have similar methods to work with public properties, as for private ones:
setPublicPropertyValue:forKey:, publicPropertyForKey:, hasPublicPropertyForKey: and removePublicPropertyForKey:.

In addition to this, Public properties are visible for other users, so if you have some GetSocialPublicUser entity, you can get his public properties:

1
NSString *value = [user publicPropertyForKey:key];
1
let value = user.publicPropertyValue(forKey: key)

Or, you can check does user have a property:

1
BOOL hasProperty = [user hasPublicPropertyForKey:key];
1
let hasProperty: Bool = user.hasPublicProperty(forKey: key)

You can get all properties as unmodifiable copy of origin map:

1
NSDictionary<NSString *, NSString *> *userProperties = [user allPublicProperties];
1
let userProperties = user.allPublicProperties()

Note

You can not modify properties with this map. Also, changes in user properties won’t affect your copy, so you need to refresh it after any user changes. To have up-to-date information, we suggest to use GetSocial SDK methods.

Batch Properties Update

If you want to perform multiple updates of user data, you can do it with UserUpdate class. It allows you update few user properties(custom and not) in one request:

1
2
3
4
5
6
7
8
9
GetSocialUserUpdate batchUpdate = [GetSocialUserUpdate new];
batchUpdate.avatarUrl = newAvatarUrl;
batchUpdate.displayName = newDisplayName;
[batchUpdate setPublicPropertyValue:newPublicValue forKey:publicProperty1];
[batchUpdate removePublicPropertyForKey:publicProperty2];
[batchUpdate setPrivatePropertyValue:privateProperty1 forKey:newPrivateValue];
[batchUpdate removePrivatePropertyForKey:privateProperty2];

[GetSocialUser setUserDetails:batchUpdate success:success failure:failure];
1
2
3
4
5
6
7
8
9
var batchUpdate = GetSocialUserUpdate()
batchUpdate.avatarUrl = newAvatarUrl
batchUpdate.displayName = newDisplayName
batchUpdate.setPublicPropertyValue(newPublicValue, forKey: publicProperty1)
batchUpdate.removePublicProperty(forKey: publicProperty2)
batchUpdate.setPrivatePropertyValue(privateProperty1, forKey: newPrivateValue)
batchUpdate.removePrivateProperty(forKey: privateProperty2)

GetSocialUser.setUserDetails(batchUpdate, success: success, failure: failure)

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.

To add a new identity use [GetSocialUser addAuthIdentity:success:conflict:failure:] method. Once it is successfully added, you can log in using that identity.

To remove identity from user use [GetSocialUser removeAuthIdentityWithProviderId:success:failure:] and pass the provider to be remove as first parameter:

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)

To get all user identities call [GetSocialUser authIdentities], it will return a dictionary of identities, where key is providerId and value is userId for that provider.

Subscribe to User Lifecycle Changes

Set your custom event handler in ViewController’s viewDidLoad method:

1
2
3
4
5
6
[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);
}];
1
2
3
4
5
6
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)")
}

Get Users

Get Current User

It is not possible to obtain the instance of a current user object, but SDK provides methods to read and update user properties via static GetSocialUser class.

Get User By ID

Public user profile is represented by GetSocialPublicUser class. Object is read-only and provide access to name, avatar url, list of identities and public properties.
The easiest way to get instance of GetSocialPublicUser is by GetSocial User Id:

The easiest way to get an instance of GetSocialPublicUser is by GetSocial User Id:

1
2
3
4
5
[GetSocial userWithId:@"GetSocial User Id" success:^(GetSocialPublicUser * _Nonnull publicUser) {
    // process user data
} failure:^(NSError * _Nonnull error) {
    // Ooops. There was some error while getting other user details.
}];
1
2
3
4
5
GetSocial.user(withId: "GetSocial User Id", success: { publicUser in
    // process user data
}, failure: { error in
    // Ooops. There was some error while getting other user details.
})

Also you can get users by their identities:

Find Users

You can find users by their display name using GetSocial findUsers:success:failure::

1
2
3
4
5
6
7
8
9
GetSocialUsersQuery *usersQuery = [GetSocialUsersQuery usersByDisplayName:@"John Doe"];
[usersQuery setLimit:10];
[GetSocial findUsers:usersQuery
    success:^(NSArray<GetSocialUserReference *> *users) {
        // Show list of users
    }
    failure:^(NSError *error) {
        // Error occured
    }];
1
2
3
4
5
6
7
let usersQuery = GetSocialUsersQuery.users(byDisplayName: "John Doe")
usersQuery.setLimit(10)
GetSocial.findUsers(usersQuery, success: { users in
    // Show list of users
}, failure: { error in
    // Error occured
})

Next Steps

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

  • Connect your user with others using our Social Graph.
  • Post to global or custom news feeds and communicate with others with Activity Feed.

Give us your feedback! Was this article helpful?

πŸ˜€ πŸ™