====== CEC iOS SDK Integration ======
iOS SDK is now available for Hyphenate Customer Engagement Cloud! When you already have an iOS app, you can simply create an “IM account” on the Hyphenate Customer Engagement Cloud and integrate the iOS SDK into your app. By doing so, you can provide customer service for users of your app.
The iOS SDK has integrated dual-channel function to ensure no loss of messages. The SDK also provides a built-in conversation UI. It would take about 5 minutes to integrate the SDK together with customer service features.
The iOS SDK supports the following features:
* Send text messages, voice messages, picture messages, and location messages.
* Receive text messages, voice messages, picture messages, file messages, and robot menu messages.
* Show the customer avatar and nickname, and the "Chat with agent" button.
* Send customer information, specify agent, specify team (See [[#step_4integrate_more_service_functions|Step 4: Integrate More Service Functions]]).
* Support notes, including text, picture and voice notes (See [[#step_5integrate_more_extended_functions|Step 5: Integrate More Extended Functions]]).
===== Step 1: Create IM Account =====
The “IM account” on the Hyphenate Customer Engagement Cloud corresponds to the application in the instant messaging (IM) console. After creating an IM account on the Hyphenate Customer Engagement Cloud, you can log in to the IM console to manage the corresponding application.
* Quick create: If you do not have an IM console account, you can click **Quick create**. The system will automatically create an IM account for you.
* Bind IM account: If you already have an IM console account and have created an application on the IM console, you can go to “Admin Mode > Channels > App”, click **Create IM Account**, click **Bind IM Account**, and then fill in the display name, AppKey, ClientId, ClientSecret, IM service ID (IM username), IM password (IM user's password) to manually bind your application to Hyphenate Customer Engagement Cloud.
For a step-by-step demonstration of creating an IM account, see [[cs-en:visitoraccess:createappchannel|Create IM Account]].
===== Step 2: Environment Preparation =====
Development Tool: Xcode.
=== Download iOS SDK ===
When you integrate the iOS SDK, you can refer to the “Mall” demo source code and EaseUI source code.
iOS SDK: [[http://www.easemob.com/download/cs|click to download]]
"Mall" demo: [[https://github.com/easemob/helpdeskdemo-ios|click to download]]
=== iOS SDK Introduction ===
The SDK directory include four folders: helpdeskdemo-ios, HelpDeskFramework, HelpDeskUI, and BaseFramework.
* **helpdeskdemo-ios**: Demo with the real-time audio and video feature. It can be run directly.
* **HelpDeskFramework**: SDKs. HelpDesk.framework contains the real-time audio and video feature; HelpDeskLite.framework does not contain the real-time audio and video feature.
* **HelpDeskUI**: UI for the conversation screen. It can be integrated to your app.
* **BaseFramework**: Dependency library that must be imported before HelpDeskFramework.
=== Precautions ===
* The iOS SDK contains IM SDK 3.x. If you need both customer service and instant messaging (IM) features, use the initialization, login, logout methods described in this document. Then, you can use IM SDK APIs without adding IM SDK to your project.\\
* A third-party library is used inside HelpDeskUI. If a conflict occurs with your third-party library when you integrate HelpDeskUI, you could remove the conflicting third-party library from HelpDeskUI. If the interface in the third-party library needs to be upgraded, please check whether to have the upgrade with caution.
For more information on how to integrate IM and customer service features at the same time, please refer to: [[http://www.imgeek.org/article/825308790|Co-development Guide of IM SDK and customer service SDK -- iOS]]
===== Step 3: Integrate the Basic Functions =====
Complete this step, and you can provide your app users with these functions: user registration, login, logout, text messages, voice messages, picture messages, and file messages.
==== Preparations ====
1. In the project, import HelpDesk.framework, HyphenateLite.framework, and the HelpDeskUI folder.There are two ways:
* Drag the above folders into the project. In the pop-up dialog box, select "Copy items if needed" and "Create groups", and click **Finish**.
* Alternatively, choose "File > Add Files to". Select the above folders from your computer, click **Options**, select "Copy items if needed" and "Create groups", and then click **Add**.
2. Select the current TARGET, choose "General > Embedded Binaries", and add the above two libraries. Then, the libraries are automatically added to "Linked Frameworks and Libraries".
3. Choose "Build Settings > Linking > Other Linker Flags", and add **-ObjC**. (Note that -OjbC is case-sensitive.)
4. Choose "Build Settings > Enable Bitcode", and set it to NO. SDK does not support bitcode.
5. In the project info.plist file, add these information properties:
* Privacy - Photo Library Usage Description
* Privacy - Microphone Usage Description
* Privacy - Camera Usage Description
6. Add the following code to the pch file or the global .h file:
#ifdef __OBJC__
#import
#import "HelpDeskUI.h"
#endif
// Add these lines if you do not need real-time audio and video
#ifdef __OBJC__
#import
#import "HelpDeskUI.h"
#endif
Note: If there is no pch file in the project, you need to create a new one and set Prefix Header as the pch file in Build Settings. For example, HelloiOS/PrefixHeader.pch.
==== Initialization ====
In the AppDelegate.m file, under didFinishLaunchingWithOptions, call the initialization method.
HOptions *option = [[HOptions alloc] init];
option.appkey = @"Your appkey"; // required. Get your appkey on the "Admin Mode > Channels > App" page
option.tenantId = @"Your tenantId"; // required. Get your tenantId on the "Admin Mode > Settings > Company" page
// Push certificate name
option.apnsCertName = @"your apnsCerName"; // required if you need APNs push
// Initialize Kefu SDK. If it fails, Kefu SDK cannot be used.
HError *initError = [[HChatClient sharedClient] initializeSDKWithOptions:option];
if (initError) { // initialization error
}
Note: In private deployment scenarios, you need to configure the server IP address and port in the initialization method. For more information, see [[cs-en:visitoraccess:private-server|SDK Private Deployment]].
==== APNs Push ====
// register for APNs push
[application registerForRemoteNotifications];
UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
After you register for APNs push, iOS will automatically call the following method and get deviceToken. You need to pass the deviceToken to SDK.
// pass the deviceToken to the SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
[[HChatClient sharedClient] bindDeviceToken:deviceToken];
}
// register for deviceToken failed
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@"error -- %@",error);
}
**APNs registration failure is usually due to the use of a generic certificate or simulator debugging. Please check the certificate and debug with a real machine. The above example is an error reported by the iOS system.**
==== Register ====
We recommend Authorized registration to prevent malicious attempts of registering fraudulent accounts.
HError *error = [[HChatClient sharedClient] registerWithUsername:@"username" password:@"password"];
error.code:
HErrorNetworkUnavailable network is not available
The HErrorUserAlreadyExist user already exists
HErrorUserAuthenticationFailed No open registration permission (Hyphenate console [open|authorized])
HErrorUserIllegalArgument username is illegal
==== Login ====
Use isLoggedInBefore (BOOL) of HChatClient to check whether a user has logged in before letting the user enter the conversation screen.
HChatClient *client = [HChatClient sharedClient];
if (client.isLoggedInBefore != YES) {
HError *error = [client loginWithUsername:@"username" password:@"password"];
if (!error) { // login successful
} else { // login failed
return;
}
}
// enter the conversation screen
HDMessageViewController *chatVC = [[HDMessageViewController alloc] initWithConversationChatter:@"IM service ID"]; // required. Get the IM service ID on the "Admin Mode > Channels > App" page
[self.navigationController pushViewController:chatVC animated:YES];
==== Logout ====
After logout, users cannot receive messages from agents.
// The argument indicates whether to unbind the devicetoken for push messages
HError *error = [[HChatClient sharedClient] logout:YES];
if (error) { // logout failed
} else {// logout successful
}
==== Conversation ====
// obtain a conversation
HConversation *conversation = [[HChatClient sharedClient].chat getConversation:@"IM service ID"]; // required. Get the IM service ID on the "Admin Mode > Channels > App" page
==== Login Status ====
if([HChatClient sharedClient].isLoggedInBefore) {
// already logged in
}else{
// not logged in
}
==== Network Listener ====
Add a network listener to show whether the server is currently connected.
// Add a network listener, usually to app initialization. The second parameter is the queue to execute the delegate. It is the main queue by default.
[[HChatClient sharedClient] addDelegate:self delegateQueue:nil];
// Remove network listener
[[HChatClient sharedClient] removeDelegate:self];
/* This method is called in the following scenarios:
* 1. The device cannot connect to the Internet after the user logs in
* 2. The network status changes after the user logs in*/
- (void)connectionStateDidChange:(HConnectionState)aConnectionState {
switch (aConnectionState) {
case HConnectionConnected: {// connected
break;
}
case HConnectionDisconnected: {// not connected
break;
}
default:
break;
}
}
// This method is called if the logged in account is deleted from the server side
- (void)userAccountDidRemoveFromServer {
}
// This method is called is the logged in account has logged in on another device
- (void)userAccountDidLoginFromOtherDevice {
}
==== Message Listener ====
// Add a message listener. The second parameter is the queue to execute the delegate. It is the main queue by default.
[[HChatClient sharedClient].chat addDelegate:self delegateQueue:nil];
// Remove message listener
[[HChatClient sharedClient].chat removeDelegate:self];
- (void)messagesDidReceive:(NSArray *)aMessages{
// receive a regular message, format:
}
- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages{
// receive a command message, format: . Command messages are not saved in the database. They are used as system notifications, such as comment updates in notes,
// and conversations served, transferred, and closed
}
- (void)messageStatusDidChange:(HMessage *)aMessage error:(HError *)aError{
// message status updated. It is used to refresh the list and display the latest status
}
- (void)messageAttachmentStatusDidChange:(HMessage *)aMessage error:(HError *)aError{
// Message sent. It is used to refresh the list and display the latest message
}
==== Upload Your App to App Store ====
In the "Mall" demo, the .a file supports x86_64, armv7, arm64 and other platforms [support models above iPhone 5 (not including) for simulators and iPhone4 (including) and above models for devices]. Before you upload your app to AppStore, you need to remove unnecessary CPU architectures. The platforms armv7 and arm64
are enough. Run these commands:
If you use HelpDesk.framework that includes real-time audio and video
[First, enter the directory that contains HelpDesk.framework]
// Remove the binary file that supports x86_64
lipo HelpDesk.framework/HelpDesk -remove x86_64 -output HelpDesk
// replace the binary file in the framework [backup is necessary]
mv HelpDesk HelpDesk.framework/HelpDesk
// Check whether the merged binary file supports armv7 and arm64. If it does, you can upload your app to the App Store
lipo -info HelpDesk.framework/HelpDesk
If you use HelpDeskLite.framework that does not include real-time audio and video
[First, enter the directory that contains HelpDeskLite.framework]
// Remove the binary file that supports x86_64
lipo HelpDeskLite.framework/HelpDeskLite -remove x86_64 -output HelpDeskLite
// replace the binary file in the framework [backup is necessary]
mv HelpDeskLite HelpDeskLite.framework/HelpDeskLite
// Check whether the merged binary file supports armv7 and arm64. If it does, you can upload your app to the App Store
lipo -info HelpDeskLite.framework/HelpDeskLite
===== Step 4: Integrate More Service Functions =====
You can pass customer profiles to Hyphenate Customer Engagement Cloud, and specify the agent or team that serves the conversations.
==== Pass Customer Profile ====
Pass user information as customer profiles to Hyphenate Customer Engagement Cloud. The information is displayed on the Profile tab on the Conversations page.
// these attributes can be default
HVisitorInfo *visitor = [[HVisitorInfo alloc] init];
visitor.name = @"Jane Doe";
visitor.qq = @"12345678";
visitor.phone = @"13636362637";
visitor.companyName = @"Hyphenate";
visitor.nickName = @"Jane";
visitor.email = @"abv@hyphenate.io";
visitor.desc = @"Hyphenate Customer Engagement Cloud";
HMessage *message = [....];// construct the message
[message addContent:visitor]; // pass the customer profile
==== Specify Agent ====
When your app user taps the "Chat" button to start a conversation, the conversation is assigned to the specified agent.
The agent account is the agent's login email address.
HMessage *message = [....];// construct a message
[message addContent:[[HAgentIdentityInfo alloc] initWithValue:@"Agent account"]];
==== Specify Team ====
When your app user taps the "Chat" button to start a conversation, the conversation is assigned to the specified team.
The name of the team must be exactly the same as the name of the team set on the Hyphenate Customer Engagement Cloud.
HMessage *message = [....];// construct a message
[message addContent:[[HQueueIdentityInfo alloc] initWithValue:@"Team name"]];
==== Remove Real-Time Audio and Video ====
The "Mall" demo contains real-time audio and video features. If you do not need real-time audio and video, you can remove the. Follow these steps: \\
1. Remove HelpDesk.framework from the project.\\
2. Import HelpDeskLite.framework.\\
3. In the pch file
Replace
#ifdef __OBJC__
#import
#import "HelpDeskUI.h"
#endif
with
#ifdef __OBJC__
#import
#import "HelpDeskUI.h"
#endif
For more information about real-time calling APIs, see [[cs-en:visitoraccess:iossdkapi|CEC iOS SDK API]].
===== Step 5: Integrate More Extended Functions =====
For information about extended functions (sending track messages, sending order messages, and note functions), see [[cs-en:visitoraccess:iossdkapi|CEC iOS SDK API]].