Initialize the SDK

Update time: 2023/02/09 05:54:05

This document describes how to initialize the NIM SDK.

Before using various functionalities of IM, you must initialize the NIM SDK. In most cases, the SDK is initialized once during the lifetime of the application.

During initialization, settings of functionalities can be configured, such as APNs push service, multi-device synchronization for the read status of messages in P2P sessions and group chats, and cloud-based storage.

Prerequisites

Before you initialize the NIM SDK, make sure:

  • You have integrated the SDK.

  • You have performed the following operations in the CommsEase console.

    Create a project and get the AppKey and App Secret of the project. The AppKey is the unique identifier of your application created in the CommsEase console. Use a separate AppKey for your application.
    1. In the left-side navigation pane, find “Application” and click “New”.
    2. Fill out basic information for the application and click “Create”.
    3. After creating an app, you can view the application in the left navigation bar. You can click `AppKey Management`, and get the AppKey and App Secret.
      • Add the AppKey to NIMSDKOption when calling the initialization method (see below for details).
      • The App Secret is used to implement dynamic login.

Initialize the SDK

Step 1: import the header file

Import the header file into the project file as required.

#import <NIMSDK/NIMSDK.h>

Step 2 (optional): configure options for initialization

You can configure the initialization options as needed. The options include parameters in NIMSDKConfig, the SDK root directory and configurations in NIMServerSetting. If these options are not configured, the default configuration will be used.

NIMSDKConfig settings

NIMSDKConfig is a singleton. Configure it before initialization. NIMSDKConfig provides options, such as automatic download of message attachments, NSFileProtectionKey, whether unsent messages are counted as unread, whether unread counts are synced across devices, HTTPS support, maximum number of retries for automatic login, and local log lifetime. You can configure custom settings as required.

View NIMSDKConfig parameters
Parameter
Description
fetchAttachmentAutomaticallyAfterReceiving Whether the attachment of a message is automatically downloaded.
  • The default value is YES. After receiving an image or video message, the SDK will automatically get the thumbnail of the image and the first frame of a video.
  • If NO, the SDK will no longer get the thumbnail. You must manually call the fetchMessageAttachment:error: method to get the attachment.
fetchAttachmentAutomaticallyAfterReceivingInChatroom Whether the attachment of a message in chat rooms is automatically downloaded. The default value is NO. The SDK will not obtain the attachments of messages in chat rooms.
fileProtectionNone Whether NSFileProtectionNone is used as NSFileProtectionKey. The defaul value is NO. The parameter is valid only if the upper layer enables Data Protection.
  • If the value is set to YES, the file protection property is NSFileProtectionNone
  • if NO, NSFileProtectionCompleteUntilFirstUserAuthentication is used.
shouldConsiderRevokedMessageUnreadCount Whether the unsent messages are counted as unread. The default value is NO.

If the value is set to YES, and the recalled message has not been read locally, then the unread count of the corresponding session will be decremented by 1 to maintain the consistency of the unread count of the most recent session.
shouldSyncUnreadCount Whether the unread count is synced across devices. The default value is NO.

If the value is set to YES, multiple devices (PC and mobile) of the same account will get synced with the unread count
shouldCountTeamNotification Whether the group notifications are counted as unread. The default value is NO.

If the value is set to YES, group notifications will be counted as unread.
enabledHttpsForInfo Enable the HTTPS protocol support for user profiles. The default value is YES. By default, data such as user avatars, group avatars, and chat room user avatars are stored on the CommsEase server, and the SDK will automatically enable HTTPS support for data transfer
  • If the value is set to NO, the SDK will not convert the URLs from HTTP to HTTPS.
  • enabledHttpsForMessage Whether HTTPS support is enabled for messages
    • The default value is YES. By default, attachments of multimedia messages, including images, videos, and audios, are stored on the CommsEase server by default. The SDK will automatically enable HTTPS support for data transfer.
    • If you need to host the data on the app server (not recommended), you can set this parameter to NO to prevent the SDK from automatically converting HTTP URLs to HTTPS URLs
    • Even if the value is set to NO, the URLs for messages sent by the SDK also use HTTPS. This setting only affects the format conversion of the URLs for receiving messages.
    maxAutoLoginRetryTimes The number of retries after automatic login failures.
    • The retries are unlimited by default.
    • If the value is set to a number greater than 0, the automatic login will retry up to maxAutoLoginRetryTimes times before successful logins. If retries fail, an error (NIMLocalErrorCodeAutoLoginRetryLimit) will be thrown.
    maximumLogDays The time to live of the local log files. The default value is 7 days. The log file older than 7 days will be cleared. Set the value greater than or equal to 2.
    animatedImageThumbnailEnabled Whether animated thumbnails are supported.
    • The default value is NO. If the source image is an animated image, the CommsEase server will return the thumbnail of the first frame of the source image.
    • If YES, the CommsEase server will return the animated image. ** The option only affects thumbnails fetched from the server, not locally generated thumbnails
    </
    thumbnailSize The size of the thumbnail of an image message. The size represents the length of an image. The length of the downloaded thumbnail will not exceed this value.
    reconnectInBackgroundStateDisabled Whether reconnecting in the background is disabled.
    • The default value is NO. By default, if an app is still running after the app is switched to the background and gets disconnected, the SDK will continue to execute the automatic reconnection mechanism.
    • If the value is set to YES, the app running in the background stop reconnecting to the server.This setting is only required for special scenarios. Proceed with caution.
    teamReceiptEnabled Whether the read receipt of group messages is enabled. The default value is NO.
    customTag Client custom info synced with multiple devices for login
    sessionDatabaseBackupEnabled Whether database backup is enabled for session data. The default value is NO.

    If the value is set to YES and the database file corrupts, the SDK will restore the backup file and reset the roaming timestamp.
    customClientType The custom client type used with multi-device login.
    chatroomMessageReceiveMinInterval The minimum time interval for the callback for receiving messages, valid range: 50 ~ 500 milliseconds. If the value is lower or higher than the boundary value, the boundary value will be used. If unspecified, use the default value
    fcsEnable The global switch of the cloud-based storage. if it is turned off, the cloud-based storage will not be enabled no matter whether the function is enabled on the server.
    fcsAuthType The authentication type of cloud-based storage. The authentication method used to download files. No authentication by default. You can set the following values:
    • 1: refer authentication
    • 2: token authentication based on time
    • 3: token authentication based on URL
    • 4: custom authentication
    If the value is set to refer authentication, you must also set the following fcsUa and facRefer
    fcsUa UserAgent of the cloud-based storage, configured for refer authentication
    fcsRefer The reference location of the cloud-based storage, configured for refer authentication.

    SDK root directory configuration

    In addition to the previous parameters of NIMSDKConfig, you can also set the root directory of the SDK by calling the setupSDKDir: method. For a better user experience, the SDK persists the application data on the local storage, such as messages and profiles. If the directory is unspecified, the data is stored in the $Document/NIMSDK directory by default.

    • This method must be called before the sharedSDK method. Otherwise, the configuration will not take effect.
    • After calling this method to set the root directory of the SDK, the temporary files generated by the SDK will not be placed in the root directory.

    Sample code:

    objc[[NIMSDKConfig sharedConfig] setupSDKDir:@"your data path"];
    

    Configure NIMServerSetting

    You can configure some settings for the CommsEase server Configure, such as CDN domain name distribution, whether a dedicated cloud is used, and the LBS domain name using NIMServerSetting.

    You must create and add the NIMServerSetting file.

    • HTTPS settings

      NIMServerSetting can enable or disable HTTPS support (httpsEnabled). This setting affects the method of uploading and downloading files using the SDK.

      • The value of httpsEnabled is set to YES. HTTPS URLs are used for uploads and the returned URLs are converted to HTTPS URLs.

      • If the value of httpsEnabled is set to NO, HTTP URLs are used for uploads, and all original URLs will be returned. The enabledHttpsForInfo and enabledHttpsForMessage will become invalid.

        Sample code:

        NIMServerSetting *setting    = [[NIMServerSetting alloc] init];
        setting.httpsEnabled = YES;
        [[NIMSDK sharedSDK] setServerSetting:setting];
        ...
        [[NIMSDK sharedSDK] registerWithOption:option];
        
    • Data centers out of China

      If your application serves users out of mainland China, you must configure LBS and link domain names in NIMServerSetting. For more information, see Configure LBS and Link domain names.

    Step 3: invoke the interface to initialize the SDK

    Initialize the SDK by calling the registerWithOption: method. Initialize the SDK at the startup of your app. You can configure the parameters of NIMSDKOption.

    NIMSDKOptionpparameters:

    Parameter Type Required Description
    appKey NSString Yes The AppKey generated in the CommsEase console.
    apnsCername NSString No The name of the APNs certificate configured in the CommsEase console.
    pkCername NSString No The name of the PushKit certificate configured in the CommsEase console.
    • NIMSDKOption provides the optionWithAppKey: to instantiate the options. The AppKey is the unique identifier of an application. Messaging between two apps with the same AppKey and different Bundle IDs can still work.

    Sample code:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        ...
        //Initialize NIM SDK at startup    
        NSString *appKey        = @"your AppKey";
        NIMSDKOption *option    = [NIMSDKOption optionWithAppKey:appKey];
        option.apnsCername      = @"your APNs cer name";
        option.pkCername        = @"your pushkit cer name";
        [[NIMSDK sharedSDK] registerWithOption:option];
        ...
    }
    

    What’s next

    After the initialization is complete, you can log in to IM.

    Additional methods

    In the NIMSDK class, additional methods are provided to facilitate development.

    Method Description
    sdkVersion Get the version number of the current NIM SDK
    appKey Get the currently registered AppKey
    currentLogFilepath Get the log path of the SDK
    Was this page helpful?
    Yes
    No
    • Prerequisites
    • Initialize the SDK
    • Step 1: import the header file
    • Step 2 (optional): configure options for initialization
    • NIMSDKConfig settings
    • SDK root directory configuration
    • Configure NIMServerSetting
    • Step 3: invoke the interface to initialize the SDK
    • What’s next
    • Additional methods