Quick Start
Update time: 2021/12/06 06:58:40
Quick start
As one of the largest and earliest instant messaging (IM) developers in China, CommsEase has accumulated more than 15-year experience in communication technology from the very first product POPO to EasyChat later offered. CommsEase has integrated highly stable and reliable IM functions of these products so that developers can integrate IM functions into their APPs at low costs.
CommsEase SDK iOS-SDK
(NIM SDK) provides a complete IM development framework for iOS mobile applications, shields its internal complex details, and provides a relatively simple API API to facilitate third-party applications to quickly integrate IM functions. The SDK is compatible with iOS 8.0+, and the Demo is compatible with iOS 9.0+.
SDK integration
NIM SDK provides two integration methods:
-
automatic integration of NIM SDK using
CocoaPods
; or -
manual integration of NIM SDK;
Furthermore, to allow developers to easily and quickly integrate IM functions into their applications, we also provide an open-source UI Kit: NIM_iOS_UIKit, which enables the chatting function using simple configuration.
Integration with CocoaPods
Before the integration, please go to the SDK download page to check the latest version and query whether the corresponding version in the local repository is the latest. If it is not the latest version, we recommend updating the local repository first to ensure that the latest SDK version can be integrated.
pod search NIMSDK_LITE //Search NIMSDK_LITE information in local repository
pod repo update //Update a local repository
CocoaPods
Detailed explanations of keywords of the integrated resources:
Key words | Contained resources |
---|---|
NIMSDK_LITE | IM |
NIMKit | NIMSDK_LITE+NIM_iOS_UIKit+third-party dependent libraries of specific versions |
NIMKit/Lite_Free | NIMSDK_LITE+NIM_iOS_UIKit+third-party dependent libraries of unrestricted versions |
For example, without NIM_iOS_UIKit
, only IM is needed to write the following content in Podfile
:
objc //IM (Instant Message) SDK
pod 'NIMSDK_LITE'
Then, the following installation command is executed:
pod install
Manual integration
- Please go to the SDK download page to get the latest version.
- Copy the decompressed NIMSDK.framework to the project folder.
- Taking Xcode Version 11.5 as the example, go to TARGETS > Project Name > General > Frameworks, Libraries, and Embedded Content, click +, and then click Add Other ... to add NIMSDK.framework. At the same time, set the Embed property setting to Embed & Sign to keep the SDK dynamic library consistent with the application signature.
So far, the SDK has been imported.
Note: As the library contains a simulator version, the packaging will fail when importing the SDK manually. So, it is necessary to strip the simulator version before packaging
- Create the script
nim_strip_archs.sh
in a specified directory, such asSupporting Files
, of the project - Add a process in
Build Phases
under the type ofNew Run Script Phase
- Add the following content to the project: /Bin/sh, your script path, such as
/bin/sh "${SRCROOT}/NIMDemo/Supporting Files/nim_strip_archs.sh"
- Copy the following into the script:
#!/bin/sh
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
echo "current binary ${binary}"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
if [ -f "$binary" ]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"
# This script loops using the frameworks embedded in the application and
# removes unused architectures.
find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK
do
FRAMEWORK_EXECUTABLE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable)
FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME"
echo "Executable is $FRAMEWORK_EXECUTABLE_PATH"
strip_invalid_archs "$FRAMEWORK_EXECUTABLE_PATH"
done
Instructions
API Call Mode
All services are called with NIM SDK in singleton mode
objc@interface NIMSDK : NSObject
/**
* Get SDK instance
*
* @return NIMSDK instance
*/
+ (instancetype)sharedSDK;
@end
Taking getting the chat management class as an example:
objcid<NIMChatManager> chatManager = [[NIMSDK sharedSDK] chatManager];
Although all CommsEase APIs are thread-safe, we strongly recommend that you call appropriate APIs on and only on the main thread.
Way of Notification
The SDK notifies the results of the upper-level API call in two ways: callback and delegate, both of which can only be triggered on the main thread.
Generally, callback APIs are reflected in the parameter completion
of corresponding APIs and can be set when they are called. A delegate requires additions to and removals from the corresponding management classes by developers in due time: we recommend registering a delegate when the corresponding ViewController or the management class is initialized and remove a delegate when the corresponding ViewController or the management class is destroyed.
For example, developers need to monitor the results of sending messages on the session page.
objc@implementation MySessionViewController
- (void)dealloc
{
...
[[NIMSDK sharedSDK].chatManager removeDelegate:self];
...
}
- (void)viewDidLoad
{
...
[[NIMSDK sharedSDK].chatManager addDelegate:self];
...
}
#pragma mark - NIMChatManagerDelegate
- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(NSError *)error
{
//Send results
}
All call errors are revealed in the form of NSError
. For different scenarios, we classify errors into the following two types of error domain and corresponding error codes:
Error Domain | Error code | Description |
---|---|---|
NIMLocalErrorDomain | NIMLocalErrorCode | Caused by local operation errors |
NIMRemoteErrorDomain | NIMRemoteErrorCode | Caused by errors in interactions with the server |
Errors encountered in the development process can be checked against error domains and error codes. Refer to NIMGlobalDefs.h
for definitions. Of course, you can also locate problems using checking the corresponding error descriptions of userInfo
in NSError in the development process.
Initialize the SDK
After the SDK is integrated into the client, the SDK needs to be initialized before using it.
NIM SDK Registration
NIM SDK is initialized by registering App Key. The initialization method should be called before using a SDK method. For regular services, the initialization method is and should be called only once.
Note: import <NIMSDK/NIMSDK.h>
is required before using the SDK.
Prototype
objc@interface NIMSDK : NSObject
/**
* Initialize SDK
*
* @param option - Registration option
*/
- (void)registerWithOption:(NIMSDKOption *)option;
@end
NIMSDKOption optional parameter list
Parameter | Type | Description |
---|---|---|
appKey | NSString | appKey allocated by CommsEase |
apnsCername | NSString | APNs push certificate name |
pkCername | NSString | PushKit push certificate name |
Note:
NIMSDKOption
provides the class method+ (instancetype)optionWithAppKey:(NSString *)appKey
to return instances.- As appKey is a unique logical identifier of an application, application messages from different Bundle IDs of the same appKey still can be interworked.
Call example
objc- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
//Recommend initializing NIMSDK at the time of program startup
NSString *appKey = @"your app key";
NIMSDKOption *option = [NIMSDKOption optionWithAppKey:appKey];
option.apnsCername = @"your APNs cer name";
option.pkCername = @"your pushkit cer name";
[[NIMSDK sharedSDK] registerWithOption:option];
...
}
Initialize the SDK of Other Configuration Parameters
NIM SDK also provides developers with additional initialization configurations for some extensions.
NIMServerSetting
NIMServerSetting
is the overall NIM server setting and needs to be created and injected by developers. One of its main functions is to select whether to enable HTTPS support:
objc@interface NIMServerSetting : NSObject
/**
* It determines to enable HTTPS support.
*/
@property (nonatomic, assign) BOOL httpsEnabled
@end
The value is "YES" by default. This attribute will affect the mode of uploading and downloading files when using the SDK. When it is set to YES, HTTPS will be used to upload files and all URL returns will try to adjust HTTP URLs to HTTPS URLs.
When it is set to NO, HTTP will be used to upload files and all URL returns will only return the original URLs without being processed. Meanwhile, NIMSDKConfig
—enabledHttpsForInfo
and enabledHttpsForMessage
will be invalid.
Example
objcNIMServerSetting *setting = [[NIMServerSetting alloc] init];
setting.enabledHttps = YES;
[[NIMSDK sharedSDK] setServerSetting:setting];
...
[[NIMSDK sharedSDK] registerWithOption:option];
NIMSDKConfig
NIMSDKConfig
is a single instance and is recommended to be configured before calling the initialization API.
Prototype
objc@interface NIMSDKConfig : NSObject
/**
* Return an instance of configuration option
*
* @return - Configuration option
*/
+ (instancetype)sharedConfig;
@end
Overview of partial major parameter configuration of NIMSDKConfig
Configuration Name | Field | Description |
---|---|---|
Whether to download attachment(s) automatically after receiving a message | fetchAttachmentAutomaticallyAfterReceiving | After receiving an image or video message, the SDK will actively fetch the thumb of the image and the first frame of the video by default and set this field to NO. Then, the SDK will not actively fetch any attachment, and developers need to manually call the attachment API based on the service logic. |
Whether to download attachment(s) automatically after receiving a message in the chat room | fetchAttachmentAutomaticallyAfterReceivingInChat room | Similar to the instruction on attachment download switch of ordinary messages, the SDK will not voluntarily fetch attachments of chat room messages. |
Whether to use NSFileProtectionNone as NSProtectionKey of CommsEase files | fileProtectionNone | The default is NO and will be valid only when the upper-level application enables Data Protection. When it is set to YES, the protection attribute of CommsEase files will be NSFileProtectionNone; when it is set to NO, the protection attribute of CommsEase files will be NSFileProtectionCompleteUntilFirstUserAuthentication. |
Whether the revoked messages should be considered to be counted into the unread count | shouldConsiderRevokedMessageUnreadCount | The value is "NO" by default. If it is set to "YES", and the revoked message is local and unread, when the message is revoked, unread count of related sessions will subtract 1 to keep consistency in unread count of recent sessions. |
Whether to synchronize the unread counts of multiple clients | shouldSyncUnreadCount | The value is "NO" by default. If it is set to "YES", multiple clients (e.g. PC and mobile client) with the same account will synchronize the unread count. |
Whether to count team notifications into the unread count | shouldCountTeamNotification | The value is "NO" by default. When it is set to YES, the team notifications received will be counted into the unread count |
Enable HTTPS support against user profile | enabledHttpsForInfo | The value is "YES" by default. By default, information such as user avatar, team avatar, user avatar in a chat room is hosted in CommsEase, so that SDK will enable HTTPS automatically. However, if you need to host this information on your server, The API shall be set to "NO", so that SDK will not transform your HTTP URL into HTTPS URL automatically. |
Enable HTTPS support against messages | enabledHttpsForMessage | The value is "YES" by default. By default, information such as image, video, and audio information is hosted in CommsEase, so that SDK will enable https automatically. However, if you need to host this information on your server, The API shall be set to "NO", so that SDK will not transform your http url into https url automatically. (Strongly discouraged) It should be noted that, even if this attribute has been set, for the messages sent out using SDK for iOS, the URL is in HTTPS. Setting this value only affects the conversion of the URL of the messages received. |
Automatic login retry times | maxAutoLoginRetryTimes | By default, automatic login will be infinitely retried. If the value is larger than 0, before successful login, automatic login will be retried for at most maxAutoLoginRetryTimes. If it is failed, the error (NIMLocalErrorCodeAutoLoginRetryLimit) will be thrown. |
Local log survival days | maximumLogDays | The default is 7 days. Logs older than 7 days will be deleted. Only the values greater than or equal to 2 can be set |
Whether to enable the animated image thumbnails | animatedImageThumbnailEnabled | The value is "NO" by default. By default, when an original image thumb is retrieved from the server, if the original image is an animated image, the thumb of the first frame of the original image will be returned. After this option is enabled, an animated image thumb will be returned. This option only affects the thumbnails retrieved from the server and will not affect the locally generated thumbnails. |
Whether to disable reconnection in the background state | reconnectInBackgroundStateDisabled | The value is "NO" by default. By default, when an application goes into the background and disconnects, if the application is still running, the SDK will enable the automatic reconnection mechanism. When it is set to YES, the automatic reconnection will be disabled in the background state and postponed to be enabled in the foreground state. This setting is only required for special user scenarios. Do not set this option without a clear reason. |
Whether to enable the team receipt | teamReceiptEnabled | The value is "NO" by default. |
Client customization information is synchronized during multi-device login | customTag | Developer customization. |
Custom client type | customClientType | Developer customization. It will be used with the custom multi-device login policy |
- Automatic support configuration of URL for HTTPS
objc@interface NIMSDKConfig : NSObject
/**
* Enable HTTPS support for user profile
* @discusssion - The value is "YES" by default. By default, information such as user avatar, team avatar, user avatar in a chat room is hosted in CommsEase, so that SDK will enable HTTPS automatically. However, if you need to host this information on your server, The API shall be set to "NO", so that SDK will not transform your http url into https url automatically.
*/
@property (nonatomic, assign) BOOL enabledHttpsForInfo
/**
* Enable HTTPS support for user content
* @discusssion - The value is "YES" by default. The value is "YES" by default. By default, information such as image, video, and audio information is hosted in CommsEase, so that SDK will enable HTTPS automatically. However, if you need to host this information on your server, The API shall be set to "NO", so that SDK will not transform your http url into https url automatically. It is noted that even if the attribute is configured, message URL that is sent with SDK for iOS is still https, and setting the value will only influence the format transformation of the received message URL. Now, we do not recommend setting the value to "NO".
*/
@property (nonatomic, assign) BOOL enabledHttpsForMessage
@end
- Set the SDK root directory
For a better application experience, the SDK needs to locally persist the application data, such as messages and user profile, to some extent. By default, all data will be placed in the directory $Document/NIMSDK.
objc@interface NIMSDKConfig : NSObject
/**
* Set SDK root directory
* @discusssion - If the value is set, all data generated by SDK (including chat history, but not including temporary files) will be stored under the directory. If it is not set, all data will be stored under the directory $Document/NIMSDK. The configuration option must be invoked before the invocation of any shared SDK API of NIMSDK, otherwise, a configuration cannot take effect.
*/
- (void)setupSDKDir:(NSString *)sdkDir;
@end
Example
objc[[NIMSDKConfig sharedConfig] setupSDKDir:@"your data path"];
Login
Before invoking SDK registration API, you shall register an IM account firstly (for once only) to register one unique account (also "accid") for each IM user of App. Developers are recommended to read here to gain further knowledge of the CommsEase account system process. Now, CommsEase can be registered by the following two methods:
- Method 1: You can complete registration by invoking The API for server API registration. It is strongly recommended now.
- Method 2: You can register on the CommsEase console page manually. Go to
CommsEase Application->Feature Management->IM Free Version->Account Management
. Note: This method can be only used at the debugging stage. IM Professional does not support this function at present.
Manual login
Manual login is required for the initial login on a new device, and the next login after being kicked out, switching to another account, and logging out. It applies to the scenario where a user enters login account and password manually.
objc@protocol NIMLoginManager <NSObject>
/**
* Login
*
* @param account - Account
* @param token - Token (login token bound at the background)
* @param completion A callback for completion
*/
- (void)login:(NSString *)account
token:(NSString *)token
completion:(NIMLoginHandler)completion;
@end
Example
objcNSString *account = @"your account";
NSString *token = @"your token";
[[[NIMSDK sharedSDK] loginManager] login:account
token:token
completion:^(NSError *error) {}];
error is the login error message, or nil for success.
automatic login
If manual login is successful, local account and password that are saved to local database are applicable for automatic login. Automatic login applies to the scenario where a user clicks the icon again to launch and log in the application without the need to enter account and password after the application is removed. At this time, the application can access the user's local SDK data when there is no network and the login is not successful. Automatic login needs to call the following APIs:
Prototype
objc@protocol NIMLoginManager <NSObject>
/**
* Automatic login
*
* @param loginData - Parameter of automatic login
* @discussion - Enable APP. If user account and token have been stored, we recommend to use this login method by which a session window can be opened without a network.
*/
- (void)autoLogin:(NIMAutoLoginData *)loginData;
@end
NIMAutoLoginData parameter list
Parameter | Type | Description |
---|---|---|
account | NSString | account |
token | NSString | token (the token bound in the background for login) |
forcedMode | BOOL | Forced mode switch |
forcedMode
in NIMAutoLoginData
is the forced mode switch. For automatic login in the non-forced mode, the server will check whether the currently logged-in device is the last logged-in device. If it is not, the server will reject this automatic login (return error code 417); for automatic login in the forced mode, the server will not check whether the current logged-in device is the last logged-in device, which is less safe, but more convenient.
Example
objcNIMAutoLoginData *loginData = [[NIMAutoLoginData alloc] init];
loginData.account = account;
loginData.token = token;
[[[NIMSDK sharedSDK] loginManager] autoLogin:loginData];
Dynamic login
For the versions before 8.3.0, the users' login credentials are accid and token. This token is a static token that will not change over time once generated unless actively changed by developers. Once they are disclosed, users' privacy will be at constant risk. A new dynamic login policy in the Version 8.3.0 generated a time-sensitive token that can effectively increase the difficulty of token cracking and reduce the impact of password disclosure.
authType and Login is added to the Version 8.3.0 using the login API to support dynamic login.
/**
* Login
*
* @param account - Account
* @param token - Token (login token bound at the background)
* @param authType - Authentication type. 0: Verification mode of original loginToken; 1: token authentication based on appSecret calculation; 2: token authentication based on the third-party invocation. The value is 0 by default.
* @param loginExt - Custom field of login. It is used to conduct login detection for the third-party callback service that is submitted to users and will not be synchronized to other clients. If authType is 2, it is used for the third-party verification.
* @param completion A callback for completion
*/
- (void)login:(NSString *)account
token:(NSString *)token
authType:(int)authType
loginExt:(NSString *)loginExt
completion:(NIMLoginHandler)completion;
-
When authType is set to 0, the original static mode will be maintained, and this is the default value;
-
When authType is set to 1, provideDynamicTokenForAccount of NIMLoginManagerDelegate needs to be realized at the same time to provide a dynamic token that will be generated by appsecret, timestamps, and other information using conventional algorithms;
-
When authType is set to 2, the field loginExt needs to be provided as a token at the same time, of which the validity will be delivered to a third-party server by the NIM server after receiving the field for verification.
Please contact the Customer Service for enabling dynamic login.
Login Status Monitoring
Applications can monitor the current login status using the following agents and delegates:
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* Login callback
*
* @param step - Login steps
* @discussion - The callback is mainly used for refreshing client UI.
*/
- (void)onLogin:(NIMLoginStep)step
@end
NIMLoginStep enumerations
Value | Description |
---|---|
NIMLoginStepLinking | Connect to server |
NIMLoginStepLinkOK | Connect to server successfully |
NIMLoginStepLinkFailed | Failed to connect to server |
NIMLoginStepLogining | Login |
NIMLoginStepLoginOK | Log in successfully |
NIMLoginStepLoginFailed | Failed to log in |
NIMLoginStepSyncing | Start synchronizing data |
NIMLoginStepSyncOK | Data synchronization completed |
NIMLoginStepLoseConnection | Disconnected |
NIMLoginStepNetChanged | Network switching |
The complete login steps are basically as follows:
- NIMLoginStepLinking
- NIMLoginStepLinkOK
- NIMLoginStepLogining
- NIMLoginStepLoginOK
- NIMLoginStepSyncing
- NIMLoginStepSyncOK
While automatic login will trigger a callback to change the above steps, when running into some errors that can't be automatically solved by the SDK, developers need to deal with the errors in the following callback.
For example, poor current network status tends to result in a network timeout error in an automatic login. At this time, the upper-level developers do not need to take action, as the SDK will reconnect constantly and strategically. However, in the event of an error in mismatch between username and password, the upper-level developers need to take appropriate actions to log out and prompt the user to log in manually or refresh the username and password from the user's application server. Some special login errors are listed in this API. we recommend considering the coping logic in integration if possible.
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* A callback for error in an automatic login
*
* @param error - Error information
* @discussion - The callback is mainly used to throw errors that cannot be solved by SDK automatically.
*/
- (void)onAutoLoginFailed:(NSError *)error
@end
Active Login Status Query
The SDK supports the active query about whether the current account is online:
objc@protocol NIMLoginManager <NSObject>
/**
* Return whether the current account is online.
*/
- (BOOL)isLogined
@end
Data synchronization
After successful login, NIM SDK will automatically synchronize team messages, offline messages, roaming messages, system notifications, and other data. The data synchronization process corresponds to the following in the callback -(void)onLogin:(NIMLoginStep)step
of the agent protocol NIMLoginManagerDelegate
:
NIMLoginStepSyncing
: start synchronizing data.NIMLoginStepSyncOK
: data synchronization completed.
The entire login process is completed after data synchronization.
Reconnection
As the SDK provides an automatic reconnection mechanism (to automatically reconnect to the NIM server and log in again), the login status for all reconnections can be called back in - (void)onLogin:(NIMLoginStep)step
.
The SDK will automatically enable the reconnection in the following two scenarios:
- Disconnection for the poor network after successful manual/automatic login.
- If the network is poor, the account password is ordinary, correct, and not disabled. When you start App, the automatic login API will be called.
If one of the above conditions is satisfied, when the user has ordinary network problems such as connection timeout, then automatic reconnection and login will be enabled and the upper developer is not required to make extra re-login logics.
The SDK will stop the reconnection when the number of retries exceeds the predetermined limit. The number of retries is defined in NIMSDKConfig
and defaults to 0, which indicates retrying without limit.
Prototype
objc@interface NIMSDKConfig : NSObject
/**
* Retry times for automatic login
* @discusssion - The value is 0 by default. By default, automatic login will be infinitely retried. If the value is larger than 0, before successful login, automatic login will be retried for at most maxAutoLoginRetryTimes. If it is failed, the error (NIMLocalErrorCodeAutoLoginRetryLimit) will be thrown.
*/
@property (nonatomic,assign) NSInteger maxAutoLoginRetryTimes;
@end
Multi-device Login and invalidate previous login
CommsEase SDK supports configuration of multiple multi-device login strategies:
- Login to only one device
- Mutual kick-out on desktop PC and Web clients, mutual kick-out on mobile Android and IOS clients, simultaneous login on desktop and mobile clients.
- Invalidate previous login in case of the same SDK;
- The mutual kick-out occurs between two same categories, for example, between Windows SDK and SDK for Web, between SDK for Android and SDK for iOS.
- Synchronous login can be realized at each client (up to 10 devices can be online synchronously).
Multi-device Login Monitoring
When a user logs in on a client, other devices that have not been kicked out will trigger a callback:
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* Change in multi-device login
*/
- (void)onMultiLoginClientsChangedWithType:(NIMMultiLoginType)type
@end
At the same time, you can query the list of the devices logged in at the current time:
objc@protocol NIMLoginManager <NSObject>
/**
* Return the list of current login devices
*/
- (NSArray<NIMLoginClient *> *)currentLoginClients;
@end
Invalidate previous login
The SDK supports the current login device to kick out other login devices:
objc@protocol NIMLoginManager <NSObject>
/**
* Kick out login at other clients
*/
- (void)kickOtherClient:(NIMLoginClient *)client
completion:(nullable NIMLoginHandler)completion
@end
When the current login client is kicked out, it can be perceived by the following callback:
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* A callback for being kicked out (server/other clients)
*/
-(void)onKick:(NIMKickReason)code
clientType:(NIMLoginClientType)clientType
@end
we recommend logging out and switching to the login page after the application receives the kicked callback.
Logout
The application layer must call the SDK logout operation when logging out. This operation will notify the NIM server to unbind the push notification information to avoid the situation where the user has logged out but the push is still sent to the current device.
objc@protocol NIMLoginManager <NSObject>
- (void)logout:(nullable NIMLoginHandler)completion
@end
Considering the user experience, the logout timeout will be shorter than that of other requests. No matter whether the logout request is successful or not, the upper application should perform logout behavior in UI performance. In case of a logout failure, developers should still jump to the login screen. The logout failure is only a failure of the NIM server to unbind APNs push information, and the local information has been cleaned up successfully.
Example:
objc[[[NIMSDK sharedSDK] loginManager] logout:^(NSError *error) {
//jump to login page
}];
Other methods
Some methods for development are provided in the class NIMSDK
and the protocol NIMLoginManager
.
- In the class
NIMSDK
:
objc@interface NIMSDK : NSObject
/**
* Get version number of current CommsEase IM-SDK
*/
- (NSString *)sdkVersion
/**
* Return current registered AppKey
*/
- (nullable NSString *)appKey
/**
* Return SDK Log path
# <span id="快速开始">Quick start</span>
As one of the largest and earliest instant messaging (IM) developers in China, CommsEase has accumulated more than 15-year experience in communication technology from the very first product POPO to EasyChat later offered. CommsEase has integrated highly stable and reliable IM functions of these products so that developers can integrate IM functions into their APPs at low costs.
CommsEase SDK `iOS-SDK` (NIM SDK) provides a complete IM development framework for iOS mobile applications, shields its internal complex details, and provides a relatively simple API API to facilitate third-party applications to quickly integrate IM functions. The SDK is compatible with iOS 8.0+, and the Demo is compatible with iOS 9.0+.
## <span id="SDK集成">SDK integration</span>
NIM SDK provides two integration methods:
- automatic integration of NIM SDK using `CocoaPods`; or
- manual integration of NIM SDK;
Furthermore, to allow developers to easily and quickly integrate IM functions into their applications, we also provide an open-source UI Kit: [NIM\_iOS\_UIKit](https://github.com/netease-im/NIM_iOS_UIKit), which enables the chatting function using simple configuration.
### <span id="CocoaPods集成">Integration with CocoaPods</span>
Before the integration, please go to the [SDK download page](http://netease.im/im-sdk-demo) to check the latest version and query whether the corresponding version in the local repository is the latest . If it is not the latest version, we recommend updating the local repository first to ensure that the latest SDK version can be integrated.
pod search NIMSDK_LITE //Search NIMSDK_LITE information in local repository
pod repo update //Update a local repository
`CocoaPods`Detailed explanations of keywords of the integrated resources:
| Key words| Contained resources
|:----------:|:----------:
| NIMSDK\_LITE| IM
| NIMKit| NIMSDK\_LITE+NIM\_iOS\_UIKit+third-party dependent libraries of [specific versions](https://github.com/netease-im/NIM_iOS_UIKit/blob/master/NIMKit.podspec)
| NIMKit/Lite\_Free| NIMSDK\_LITE+NIM\_iOS\_UIKit+third-party dependent libraries of unrestricted versions
For example, without `NIM_iOS_UIKit`, only IM is needed to write the following content in `Podfile`:
```objc
//IM (Instant Message) SDK
pod 'NIMSDK_LITE'
Then, the following installation command is executed:
pod install
Manual integration
- Please go to the SDK download page to get the latest version.
- Copy the decompressed NIMSDK.framework to the project folder.
- Taking Xcode Version 11.5 as the example, go to TARGETS > Project Name > General > Frameworks, Libraries, and Embedded Content, click +, and then click Add Other ... to add NIMSDK.framework. At the same time, set the Embed property setting to Embed & Sign to keep the SDK dynamic library consistent with the application signature.
So far, the SDK has been imported.
Note: As the library contains a simulator version, the packaging will fail when importing the SDK manually. So, it is necessary to strip the simulator version before packaging
- Create the script
nim_strip_archs.sh
in a specified directory, such asSupporting Files
, of the project - Add a process in
Build Phases
under the type ofNew Run Script Phase
- Add the following content to the project: /Bin/sh, your script path, such as
/bin/sh "${SRCROOT}/NIMDemo/Supporting Files/nim_strip_archs.sh"
- Copy the following into the script:
#!/bin/sh
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
echo "current binary ${binary}"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
if [ -f "$binary" ]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"
# This script loops using the frameworks embedded in the application and
# removes unused architectures.
find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK
do
FRAMEWORK_EXECUTABLE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable)
FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME"
echo "Executable is $FRAMEWORK_EXECUTABLE_PATH"
strip_invalid_archs "$FRAMEWORK_EXECUTABLE_PATH"
done
Instructions
API Call Mode
All services are called with NIM SDK in singleton mode
objc@interface NIMSDK : NSObject
/**
* Get SDK instance
*
* @return NIMSDK instance
*/
+ (instancetype)sharedSDK;
@end
Taking getting the chat management class as an example:
objcid<NIMChatManager> chatManager = [[NIMSDK sharedSDK] chatManager];
Although all CommsEase APIs are thread-safe, we strongly recommend that you call appropriate APIs on and only on the main thread.
Way of Notification
The SDK notifies the results of the upper-level API call in two ways: callback and delegate, both of which can only be triggered on the main thread.
Generally, callback APIs are reflected in the parameter completion
of corresponding APIs and can be set when they are called. A delegate requires additions to and removals from the corresponding management classes by developers in due time: it is generally recommended to register a delegate when the corresponding ViewController or the management class is initialized and remove a delegate when the corresponding ViewController or the management class is destroyed.
For example, developers need to monitor the results of sending messages on the session page.
objc@implementation MySessionViewController
- (void)dealloc
{
...
[[NIMSDK sharedSDK].chatManager removeDelegate:self];
...
}
- (void)viewDidLoad
{
...
[[NIMSDK sharedSDK].chatManager addDelegate:self];
...
}
#pragma mark - NIMChatManagerDelegate
- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(NSError *)error
{
//Send results
}
All call errors are revealed in the form of NSError
. For different scenarios, we classify errors into the following two types of error domain and corresponding error codes:
Error Domain | Error code | Description |
---|---|---|
NIMLocalErrorDomain | NIMLocalErrorCode | Caused by local operation errors |
NIMRemoteErrorDomain | NIMRemoteErrorCode | Caused by errors in interactions with the server |
Errors encountered in the development process can be checked against error domains and error codes. Refer to NIMGlobalDefs.h
for definitions. Of course, you can also locate problems using checking the corresponding error descriptions of userInfo
in NSError in the development process.
Initialize the SDK
After the SDK is integrated into the client, the SDK needs to be initialized before using it.
NIM SDK Registration
NIM SDK is initialized by registering App Key. The initialization method should be called before using a SDK method. For regular services, the initialization method is and should be called only once.
Note: import <NIMSDK/NIMSDK.h>
is required before using the SDK.
Prototype
objc@interface NIMSDK : NSObject
/**
* Initialize SDK
*
* @param option - Registration option
*/
- (void)registerWithOption:(NIMSDKOption *)option;
@end
NIMSDKOption optional parameter list
Parameter | Type | Description |
---|---|---|
appKey | NSString | appKey allocated by CommsEase |
apnsCername | NSString | APNs push certificate name |
pkCername | NSString | PushKit push certificate name |
Note:
NIMSDKOption
provides the class method+ (instancetype)optionWithAppKey:(NSString *)appKey
to return instances.- As appKey is a unique logical identifier of an application, application messages from different Bundle IDs of the same appKey still can be interworked.
Call example
objc- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
//Recommend initializing NIMSDK at the time of program startup
NSString *appKey = @"your app key";
NIMSDKOption *option = [NIMSDKOption optionWithAppKey:appKey];
option.apnsCername = @"your APNs cer name";
option.pkCername = @"your pushkit cer name";
[[NIMSDK sharedSDK] registerWithOption:option];
...
}
Initialize the SDK of Other Configuration Parameters
NIM SDK also provides developers with additional initialization configurations for some extensions.
NIMServerSetting
NIMServerSetting
is the overall NIM server setting and needs to be created and injected by developers. One of its main functions is to select whether to enable HTTPS support:
objc@interface NIMServerSetting : NSObject
/**
* It determines to enable HTTPS support.
*/
@property (nonatomic, assign) BOOL httpsEnabled
@end
The value is "YES" by default. This attribute will affect the mode of uploading and downloading files when using the SDK. When it is set to YES, HTTPS will be used to upload files and all URL returns will try to adjust HTTP URLs to HTTPS URLs.
When it is set to NO, HTTP will be used to upload files and all URL returns will only return the original URLs without being processed. Meanwhile, NIMSDKConfig
—enabledHttpsForInfo
and enabledHttpsForMessage
will be invalid.
Example
objcNIMServerSetting *setting = [[NIMServerSetting alloc] init];
setting.enabledHttps = YES;
[[NIMSDK sharedSDK] setServerSetting:setting];
...
[[NIMSDK sharedSDK] registerWithOption:option];
NIMSDKConfig
NIMSDKConfig
is a single instance and is recommended to be configured before calling the initialization API.
Prototype
objc@interface NIMSDKConfig : NSObject
/**
* Return an instance of configuration option
*
* @return - Configuration option
*/
+ (instancetype)sharedConfig;
@end
Overview of partial major parameter configuration of NIMSDKConfig
Configuration Name | Field | Description |
---|---|---|
Whether to download attachment(s) automatically after receiving a message | fetchAttachmentAutomaticallyAfterReceiving | After receiving an image or video message, the SDK will actively fetch the thumb of the image and the first frame of the video by default and set this field to NO. Then, the SDK will not actively fetch any attachment, and developers need to manually call the attachment API based on the service logic. |
Whether to download attachment(s) automatically after receiving a message in the chat room | fetchAttachmentAutomaticallyAfterReceivingInChat room | Similar to the instruction on attachment download switch of ordinary messages, the SDK will not voluntarily fetch attachments of chat room messages. |
Whether to use NSFileProtectionNone as NSProtectionKey of CommsEase files | fileProtectionNone | The default is NO and will be valid only when the upper-level application enables Data Protection. When it is set to YES, the protection attribute of CommsEase files will be NSFileProtectionNone; when it is set to NO, the protection attribute of CommsEase files will be NSFileProtectionCompleteUntilFirstUserAuthentication. |
Whether the revoked messages should be considered to be counted into the unread count | shouldConsiderRevokedMessageUnreadCount | The value is "NO" by default. If it is set to "YES", and the revoked message is local and unread, when the message is revoked, unread count of related sessions will subtract 1 to keep consistency in unread count of recent sessions. |
Whether to synchronize the unread counts of multiple clients | shouldSyncUnreadCount | The value is "NO" by default. If it is set to "YES", multiple clients (e.g. PC and mobile client) with the same account will synchronize the unread count. |
Whether to count team notifications into the unread count | shouldCountTeamNotification | The value is "NO" by default. When it is set to YES, the team notifications received will be counted into the unread count |
Enable HTTPS support against user profile | enabledHttpsForInfo | The value is "YES" by default. By default, information such as user avatar, team avatar, user avatar in a chat room is hosted in CommsEase, so that SDK will enable HTTPS automatically. However, if you need to host the information in your server, The API shall be set to "NO", so that SDK will not transform your HTTP URL into HTTPS URL automatically. |
Enable HTTPS support against messages | enabledHttpsForMessage | The value is "YES" by default. By default, information such as image, video, and audio information is hosted in CommsEase, so that SDK will enable https automatically. However, if you need to host the information in your server, The API shall be set to "NO", so that SDK will not transform your HTTP URL into https url automatically (Strongly discouraged). It should be noted that, even if this attribute has been set, for the messages sent out using SDK for iOS, the URL is in HTTPS. Setting this value only affects the conversion of the URL of the messages received. |
Automatic login retry times | maxAutoLoginRetryTimes | By default, automatic login will be infinitely retried. If the value is larger than 0, before successful login, automatic login will be retried for at most maxAutoLoginRetryTimes. If it is failed, the error (NIMLocalErrorCodeAutoLoginRetryLimit) will be thrown. |
Local log survival days | maximumLogDays | The default is 7 days. Logs older than 7 days will be deleted. Only the values greater than or equal to 2 can be set |
Whether to enable the animated image thumbnails | animatedImageThumbnailEnabled | The value is "NO" by default. By default, when an original image thumb is retrieved from the server, if the original image is an animated image, the thumb of the first frame of the original image will be returned. After this option is enabled, an animated image thumb will be returned. This option only affects the thumbnails retrieved from the server and will not affect the locally generated thumbnails. |
Whether to disable reconnection in the background state | reconnectInBackgroundStateDisabled | The value is "NO" by default. By default, when an application goes into the background and disconnects, if the application is still running, the SDK will enable the automatic reconnection mechanism. When it is set to YES, the automatic reconnection will be disabled in the background state and postponed to be enabled in the foreground state. This setting is only required for special user scenarios. Do not set this option without a clear reason. |
Whether to enable the team receipt | teamReceiptEnabled | The value is "NO" by default. |
Client customization information is synchronized during multi-device login | customTag | Developer customization. |
Custom client type | customClientType | Developer customization. It will be used with the custom multi-device login policy |
- Automatic support configuration of URL for HTTPS
objc@interface NIMSDKConfig : NSObject
/**
* Enable HTTPS support for user profile
* @discusssion - The value is "YES" by default. By default, information such as user avatar, team avatar, user avatar in a chat room is hosted in CommsEase, so that SDK will enable HTTPS automatically. However, if you need to host the information in your server, The API shall be set to "NO", so that SDK will not transform your HTTP URL into HTTPs URL automatically.
*/
@property (nonatomic, assign) BOOL enabledHttpsForInfo
/**
* Enable HTTPS support for user content
* @discusssion - The value is "YES" by default. The value is "YES" by default. By default, information such as image, video, and audio information is hosted in CommsEase, so that SDK will enable HTTPS automatically. However, if you need to host the information in your server, The API shall be set to "NO", so that SDK will not transform your HTTP URL into HTTPS URL automatically. It is noted that even if the attribute is configured, message URL that is sent with SDK for iOS is still HTTPS, and setting the value will only influence the format transformation of the received message URL. Now, we do not recommend setting the value to "NO".
*/
@property (nonatomic, assign) BOOL enabledHttpsForMessage
@end
- Set the SDK root directory
For a better application experience, the SDK needs to locally persist the application data, such as messages and user profile, to some extent. By default, all data will be placed in the directory $Document/NIMSDK.
objc@interface NIMSDKConfig : NSObject
/**
* Set SDK root directory
* @discusssion - If the value is set, all data generated by SDK (including chat history, but not including temporary files) will be stored under the directory. If it is not set, all data will be stored under the directory $Document/NIMSDK. The configuration option must be invoked before the invocation of any shared SDK API of NIMSDK, otherwise, a configuration cannot take effect.
*/
- (void)setupSDKDir:(NSString *)sdkDir;
@end
Example
objc[[NIMSDKConfig sharedConfig] setupSDKDir:@"your data path"];
Login
Before invoking the SDK registration API, you shall register an IM account firstly (for once only) to register one unique account (also "accid") for each IM user of App. Developers are recommended to read here to gain further knowledge of the CommsEase account system process. Now, CommsEase can be registered by the following two methods:
- Method 1: You can complete registration by invoking The API for server API registration. It is strongly recommended now.
- Method 2: You can register on the CommsEase console page manually. Go to
CommsEase Application->Feature Management->IM Free Version->Account Management
. Note: This method can be only used at the debugging stage. IM Professional does not support this function at present.
Manual login
Manual login is required for the initial login on a new device, and the next login after being kicked out, switching to another account, and logging out. It applies to the scenario where a user enters login account and password manually.
objc@protocol NIMLoginManager <NSObject>
/**
* Login
*
* @param account - Account
* @param token - Token (login token bound at the background)
* @param completion A callback for completion
*/
- (void)login:(NSString *)account
token:(NSString *)token
completion:(NIMLoginHandler)completion;
@end
Example
objcNSString *account = @"your account";
NSString *token = @"your token";
[[[NIMSDK sharedSDK] loginManager] login:account
token:token
completion:^(NSError *error) {}];
error is the login error message or nil for success.
automatic login
If manual login is successful, local account and password that is saved to the local database are applicable for automatic login. Automatic login applies to the scenario where a user clicks the icon again to launch and log in the application without the need to enter an account and password after the application is removed. At this time, the application can access the user's local SDK data when there is no network and the login is not successful. Automatic login needs to call the following APIs:
Prototype
objc@protocol NIMLoginManager <NSObject>
/**
* Automatic login
*
* @param loginData - Parameter of automatic login
* @discussion - Enable APP. If user account and token have been stored, we recommend to use this login method by which a session window can be opened without a network.
*/
- (void)autoLogin:(NIMAutoLoginData *)loginData;
@end
NIMAutoLoginData parameter list
Parameter | Type | Description |
---|---|---|
account | NSString | account |
token | NSString | token (the token bound in the background for login) |
forcedMode | BOOL | Forced mode switch |
forcedMode
in NIMAutoLoginData
is the forced mode switch. For automatic login in the non-forced mode, the server will check whether the currently logged-in device is the last logged-in device. If it is not, the server will reject this automatic login (return error code 417); for automatic login in the forced mode, the server will not check whether the current logged-in device is the last logged-in device, which is less safe, but more convenient.
Example
objcNIMAutoLoginData *loginData = [[NIMAutoLoginData alloc] init];
loginData.account = account;
loginData.token = token;
[[[NIMSDK sharedSDK] loginManager] autoLogin:loginData];
Dynamic login
For the versions before 8.3.0, the users' login credentials are accid and token. This token is a static token that will not change over time once generated unless actively changed by developers. Once they are disclosed, users' privacy will be at constant risk. A new dynamic login policy in the Version 8.3.0 generated a time-sensitive token that can effectively increase the difficulty of token cracking and reduce the impact of password disclosure.
authType and Login are added to the Version 8.3.0 using the login API to support dynamic login.
/**
* Login
*
* @param account - Account
* @param token - Token (login token bound at the background)
* @param authType - Authentication type. 0: Verification mode of original loginToken; 1: token authentication based on appSecret calculation; 2: token authentication based on the third-party invocation. The value is 0 by default.
* @param loginExt - Custom field of login. It is used to conduct login detection for the third-party callback service that is submitted to users and will not be synchronized to other clients. If authType is 2, it is used for third-party verification.
* @param completion A callback for completion
*/
- (void)login:(NSString *)account
token:(NSString *)token
authType:(int)authType
loginExt:(NSString *)loginExt
completion:(NIMLoginHandler)completion;
-
When authType is set to 0, the original static mode will be maintained, and this is the default value;
-
When authType is set to 1, provideDynamicTokenForAccount of NIMLoginManagerDelegate needs to be realized at the same time to provide a dynamic token that will be generated by appsecret, timestamps, and other information using conventional algorithms;
-
When authType is set to 2, the field loginExt needs to be provided as a token at the same time, of which the validity will be delivered to a third-party server by the NIM server after receiving the field for verification.
Please contact Customer Service for enabling dynamic login.
Login Status Monitoring
Applications can monitor the current login status using the following agents and delegates:
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* Login callback
*
* @param step - Login steps
* @discussion - The callback is mainly used for refreshing client UI.
*/
- (void)onLogin:(NIMLoginStep)step
@end
NIMLoginStep enumerations
Value | Description |
---|---|
NIMLoginStepLinking | Connect to server |
NIMLoginStepLinkOK | Connect to server successfully |
NIMLoginStepLinkFailed | Failed to connect to server |
NIMLoginStepLogining | Login |
NIMLoginStepLoginOK | Log in successfully |
NIMLoginStepLoginFailed | Failed to log in |
NIMLoginStepSyncing | Start synchronizing data |
NIMLoginStepSyncOK | Data synchronization completed |
NIMLoginStepLoseConnection | Disconnected |
NIMLoginStepNetChanged | Network switching |
The complete login steps are basically as follows:
- NIMLoginStepLinking
- NIMLoginStepLinkOK
- NIMLoginStepLogining
- NIMLoginStepLoginOK
- NIMLoginStepSyncing
- NIMLoginStepSyncOK
While automatic login will trigger a callback to change the above steps, when running into some errors that can't be automatically solved by the SDK, developers need to deal with the errors in the following callback.
For example, poor current network status tends to result in a network timeout error in an automatic login. At this time, the upper-level developers do not need to take action, as the SDK will reconnect constantly and strategically. However, in the event of an error in a mismatch between username and password, the upper-level developers need to take appropriate actions to log out and prompt the user to log in manually or refresh the username and password from the user's application server. Some special login errors are listed in this API. we recommend to consider the coping logic in integration if possible.
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* A callback for error in an automatic login
*
* @param error - Error information
* @discussion - The callback is mainly used to throw errors that cannot be solved by SDK automatically.
*/
- (void)onAutoLoginFailed:(NSError *)error
@end
Active Login Status Query
The SDK supports the active query about whether the current account is online:
objc@protocol NIMLoginManager <NSObject>
/**
* Return whether the current account is online.
*/
- (BOOL)isLogined
@end
Data synchronization
After successful login, NIM SDK will automatically synchronize team messages, offline messages, roaming messages, system notifications, and other data. The data synchronization process corresponds to the following in the callback -(void)onLogin:(NIMLoginStep)step
of the agent protocol NIMLoginManagerDelegate
:
NIMLoginStepSyncing
: start synchronizing data.NIMLoginStepSyncOK
: data synchronization completed.
The entire login process is completed after data synchronization.
Reconnection
As the SDK provides an automatic reconnection mechanism (to automatically reconnect to the NIM server and log in again), the login status for all reconnections can be called back in - (void)onLogin:(NIMLoginStep)step
.
The SDK will automatically enable the reconnection in the following two scenarios:
- Disconnection for the poor network after successful manual/automatic login.
- If the network is poor, the account password is ordinary, correct, and not disabled. When you start App, the automatic login API will be called.
If one of the above conditions is satisfied, when the user has ordinary network problems such as connection timeout, then automatic reconnection and login will be enabled and the upper developer is not required to make extra re-login logics.
The SDK will stop the reconnection when the number of retries exceeds the predetermined limit. The number of retries is defined in NIMSDKConfig
and defaults to 0, which indicates retrying without limit.
Prototype
objc@interface NIMSDKConfig : NSObject
/**
* Retry times for automatic login
* @discusssion - The value is 0 by default. By default, automatic login will be infinitely retried. If the value is larger than 0, before successful login, automatic login will be retried for at most maxAutoLoginRetryTimes. If it is failed, the error (NIMLocalErrorCodeAutoLoginRetryLimit) will be thrown.
*/
@property (nonatomic,assign) NSInteger maxAutoLoginRetryTimes;
@end
Multi-device Login and invalidate previous login
CommsEase SDK supports configuration of multiple multi-device login strategies:
- Login to only one device
- Mutual kick-out on desktop PC and Web clients, mutual kick-out on mobile Android and IOS clients, simultaneous login on desktop and mobile clients.
- Mutual kick-out in case of the same SDK;
- The mutual kick-out occurs between two same categories, for example, between Windows SDK and SDK for Web, between SDK for Android and SDK for iOS.
- Synchronous login can be realized at each client (up to 10 devices can be online synchronously).
Multi-device Login Monitoring
When a user logs in on a client, other devices that have not been kicked out will trigger a callback:
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* Change in multi-device login
*/
- (void)onMultiLoginClientsChangedWithType:(NIMMultiLoginType)type
@end
At the same time, you can query the list of the devices logged in at the current time:
objc@protocol NIMLoginManager <NSObject>
/**
* Return the list of current login devices
*/
- (NSArray<NIMLoginClient *> *)currentLoginClients;
@end
Invalidate previous login
The SDK supports the current login device to kick out other login devices:
objc@protocol NIMLoginManager <NSObject>
/**
* Kick out login at other clients
*/
- (void)kickOtherClient:(NIMLoginClient *)client
completion:(nullable NIMLoginHandler)completion
@end
When the current login client is kicked out, it can be perceived by the following callback:
objc@protocol NIMLoginManagerDelegate <NSObject>
/**
* A callback for being kicked out (server/other clients)
*/
-(void)onKick:(NIMKickReason)code
clientType:(NIMLoginClientType)clientType
@end
we recommend to log out and switch to the login page after the application receives the kicked callback.
Logout
The application layer must call the SDK logout operation when logging out. This operation will notify the NIM server to unbind the push notification information to avoid the situation where the user has logged out but the push is still sent to the current device.
objc@protocol NIMLoginManager <NSObject>
- (void)logout:(nullable NIMLoginHandler)completion
@end
Considering the user experience, the logout timeout will be shorter than that of other requests. No matter whether the logout request is successful or not, the upper application should perform logout behavior in UI performance. In case of a logout failure, developers should still jump to the login screen. The logout failure is only a failure of the NIM server to unbind APNs push information, and the local information has been cleaned up successfully.
Example:
objc[[[NIMSDK sharedSDK] loginManager] logout:^(NSError *error) {
//jump to login page
}];
Other methods
Some methods for development are provided in the class NIMSDK
and the protocol NIMLoginManager
.
- In the class
NIMSDK
:
objc@interface NIMSDK : NSObject
/**
* Get version number of current CommsEase IM-SDK
*/
- (NSString *)sdkVersion
/**
* Return current registered AppKey
*/
- (nullable NSString *)appKey
/**
* Return SDK Log path
*/
- (NSString *)currentLogFilepath
@end
- In the protocol
NIMLoginManager
:
objc@protocol NIMLoginManager <NSObject>
/**
* Return current login account. If login is not successful, null character string "" will be returned here.
*/
- (NSString *)currentAccount
/**
* Query server time. The API is designed with invocation control. If the invocation is failed, the last time will be returned by default.
*/
- (void)queryServerTimeCompletion:(NIMLoginGetServerTimeHandle)completion
@end
*/
- (NSString *)currentLogFilepath @end
- In the protocol `NIMLoginManager`:
```objc
@protocol NIMLoginManager <NSObject>
/**
* Return current login account. If login is not successful, null character string "" will be returned here.
*/
- (NSString *)currentAccount
/**
* Query server time. The API is designed with invocation control. If the invocation is failed, the last time will be returned by default.
*/
- (void)queryServerTimeCompletion:(NIMLoginGetServerTimeHandle)completion
@end