Authenticate and manage a session
Initialize OpenIM iOS SDK, log in, query session state, and safely log out the current account.
The OpenIM iOS SDK establishes and maintains user sessions through authentication APIs. Before starting authentication, verify that you completed the server, user credential, and Xcode setup outlined in Before you start.
The complete session management flow is:
- Initialize the SDK with
OIMInitConfig, registering connection, token, and kick-out callbacks. - Obtain the target
userIDand authentication token from your business backend. - Invoke
login:token:onSuccess:onFailure:, await the success callback, and wait for theonConnectSuccessevent. - Once the connection is ready, query user profiles, conversations, groups, and message history.
- On account logout or switching, invoke
logoutWithOnSuccess:onFailure:and tear down local session state.
Retrieve login credentials
Retrieve the authenticated user's userID and OpenIM token from your application backend. The userID represents the unique OpenIM identity and must match the issued token.
The iOS client utilizes tokens generated by your backend; it does not issue tokens or create OpenIM users directly.
Initialize and observe connection lifecycles
Connection, token expiration, and kick-out listeners are passed directly into the initialization routine, preventing any race condition between login calls and event registration. For comprehensive OIMInitConfig parameters, consult Integrate for the runtime environment.
Code example
OIMInitConfig *config = [OIMInitConfig new];
config.platform = iPhone;
config.apiAddr = apiAddr;
config.wsAddr = wsAddr;
BOOL accepted = [[OIMManager manager]
initSDKWithConfig:config
onConnecting:^{ [sessionState setConnecting]; }
onConnectFailure:^(NSInteger code, NSString *message) {
[sessionState setFailedWithCode:code message:message];
}
onConnectSuccess:^{ [sessionState setConnected]; }
onKickedOffline:^{ [sessionState clearForForcedLogout]; }
onUserTokenExpired:^{ [sessionState refreshCredentials]; }
onUserTokenInvalid:^(NSString *message) {
[sessionState requireSignInWithMessage:message];
}];Return value
A YES return value from initSDKWithConfig:... signifies that the SDK successfully parsed the configuration and launched local services. It does not mean the user is logged in or that the WebSocket channel has connected. Perform initialization once per application process.
These callbacks are retained by the initialization manager and carry no business entity merge keys; scope their state strictly to the active user session. When tearing down or switching accounts, cancel pending background tasks to avoid stale callbacks executing against new accounts.
Log in the current user
Pass the userID and authentication token issued by your backend to login:token:onSuccess:onFailure::
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
userID | NSString * | Yes | The unique OpenIM user identifier. |
token | NSString * | Yes | The authentication token issued by OpenIMServer corresponding to userID. |
Code example
[[OIMManager manager] login:userID
token:token
onSuccess:^(NSString *data) {
// Authentication request accepted; await onConnectSuccess before querying data.
}
onFailure:^(NSInteger code, NSString *message) {
NSLog(@"OpenIMSDK login failed: %ld %@", (long)code, message);
}];Return value
The onSuccess callback confirms that identity authentication passed at the server level. The WebSocket connection becomes fully active when the onConnectSuccess initialization block executes. These are distinct milestones: always await onConnectSuccess before executing data synchronization or sending messages.
Avoid triggering parallel login requests. Disable login triggers or check for OIMLoginStatusLogging while a login operation is in flight.
Query login state
Query the current session state and authenticated user ID synchronously without passing parameters:
OIMLoginStatus status = [[OIMManager manager] getLoginStatus];
if (status == OIMLoginStatusLogged) {
NSString *currentUserID = [[OIMManager manager] getLoginUserID];
[sessionState restoreForUserID:currentUserID];
}| Value | Code | Description |
|---|---|---|
OIMLoginStatusLogout | 1 | The SDK is currently logged out. |
OIMLoginStatusLogging | 2 | Login is actively in progress; do not trigger duplicate calls. |
OIMLoginStatusLogged | 3 | The SDK session is authenticated. Verify network connectivity via connection callbacks. |
getLoginUserID synchronously returns the active user ID. Use it to verify that the app-level account aligns with the SDK session. These methods capture current snapshots and do not emit lifecycle callbacks.
When switching accounts, do not initiate a login while another session is active. Wait for the previous account logout to complete, reset application caches, and then authenticate the new credentials.
Handle token expiration and kick-outs
When onUserTokenExpired or onUserTokenInvalid triggers, request new credentials from your application backend and re-authenticate. The iOS client consumes OpenIM tokens directly without distinguishing between access and session tokens; token validity, renewal, and revocation are managed server-side.
When onKickedOffline fires, the SDK has terminated the local session due to another device login. Handle this event by clearing local user views, cancelling background jobs, and prompting the user to re-authenticate.
Log out explicitly
Invoke logoutWithOnSuccess:onFailure: when the user logs out or switches accounts:
Code example
[[OIMManager manager] logoutWithOnSuccess:^(NSString *data) {
[sessionState clearCurrentSession];
} onFailure:^(NSInteger code, NSString *message) {
NSLog(@"OpenIMSDK logout failed: %ld %@", (long)code, message);
}];Return value
The onSuccess callback signifies that the logout request completed and the current session is terminated. Callback completion, network teardown, and view model resets represent separate phases. Wait for the logout callback to succeed before flushing conversation caches, unread counts, and active message views.
When switching users, wait for the old account's logout callback to succeed and unregister delegates before logging in the new account. Avoid running concurrent login and logout operations.
Invoke unInitSDK only when the application process terminates or completely ceases using the SDK. Do not invoke unInitSDK during routine screen transitions or ordinary logouts.
Next steps
Was this page helpful?