iOS即时通讯-环信API的使用总结

环信SDK的使用

在苹果开发者网站进行制作推送证书

制作推送证书时需根据开发环境不同申请所需的证书类型:
1)对于开发环境(sandbox)的推送证书,请选择 Apple Push Notification service SSL (Sandbox)
2)对于生产环境(production)的推送证书,请选择 Apple Push Notification service SSL (Production)

证书申请完之后下载并用钥匙串打开导出为P12格式.

登录环信管理后台,创建应用,将对应的信息填写完整后,上传在苹果开发者账号中申请的推送证书

环信SDK的导入

1)手动导入:从环信官网下载HyphenateLite SDK 导入到工程目录中,并添加所需的依赖库;
2)自动导入:用cocopods导入,在工程中创建podfile文件,并pod ‘HyphenateLite_CN’;

环信SDK的基础功能

配置聊天账号

a.初始化SDK
第一步: 引入相关头文件 #import
第二步: 在工程的 AppDelegate 中的以下方法中,调用 SDK 对应方法。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //AppKey:注册的AppKey,详细见下面注释。
    //apnsCertName:推送证书名(不需要加后缀),详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:@"douser#istore"];
    options.apnsCertName = @"istore_dev";
    [[EMClient sharedClient] initializeSDKWithOptions:options];

    return YES;
}

// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

b.注册

EMError *error = [[EMClient sharedClient] registerWithUsername:@"8001" password:@"111111"];
if (error==nil) {
    NSLog(@"注册成功");
}

c.登录

EMError *error = [[EMClient sharedClient] loginWithUsername:@"8001" password:@"111111"];
if (!error) {
    NSLog(@"登录成功");
}

d.自动登录

BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
if (!isAutoLogin) {
    EMError *error = [[EMClient sharedClient] loginWithUsername:@"8001" password:@"111111"];
}

e.重连

/*!
 *  SDK连接服务器的状态变化时会接收到该回调
 *
 *  有以下几种情况,会引起该方法的调用:
 *  1. 登录成功后,手机无法上网时,会调用该回调
 *  2. 登录成功后,网络状态变化时,会调用该回调
 *
 *  @param aConnectionState 当前状态
 */
- (void)didConnectionStateChanged:(EMConnectionState)aConnectionState;

f.退出登录

EMError *error = [[EMClient sharedClient] logout:YES];
if (!error) {
     NSLog(@"退出成功");
}

g.被动退出登录

/*!
 *  当前登录账号在其它设备登录时会接收到该回调
 */
- (void)didLoginFromOtherDevice;

/*!
 *  当前登录账号已经被从服务器端删除时会收到该回调
 */
- (void)didRemovedFromServer;

快速集成群聊功能

a.创建群组

EMError *error = nil;
EMGroupOptions *setting = [[EMGroupOptions alloc] init];
setting.maxUsersCount = 500;
setting.style = EMGroupStylePublicOpenJoin;// 创建不同类型的群组,这里需要才传入不同的类型
EMGroup *group = [[EMClient sharedClient].groupManager createGroupWithSubject:@"群组名称" description:@"群组描述" invitees:@[@"6001",@"6002"] message:@"邀请您加入群组" setting:setting error:&error];
if(!error){
    NSLog(@"创建成功 -- %@",group);
}

b.初始化聊天界面(需导入EaseUI)

//群ID:@"groupId"
//聊天类型:EMConversationTypeGroupChat
EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:@"groupId" conversationType:EMConversationTypeGroupChat];

快速集成好友功能

a.添加好友

[[EMClient sharedClient].contactManager addContact:@"8001"
                                           message:@"我想加您为好友"
                                        completion:^(NSString *aUsername, EMError *aError) {
                                            if (!aError) {
                                                NSLog(@"邀请发送成功");
                                            }
                                        }];

//同意好友申请
[[EMClient sharedClient].contactManager approveFriendRequestFromUser:@"8001"
                                                          completion:^(NSString *aUsername, EMError *aError) {
                                                              if (!aError) {
                                                                  NSLog(@"同意好友成功");
                                                              }
                                                          }];

//拒绝好友申请
[[EMClient sharedClient].contactManager declineFriendRequestFromUser:@"8001"
                                                          completion:^(NSString *aUsername, EMError *aError) {
                                                              if (!aError) {
                                                                  NSLog(@"拒绝好友成功");
                                                              }
                                                          }];

b.删除好友

// 删除好友
[[EMClient sharedClient].contactManager deleteContact:@"8001"
                                           completion:^(NSString *aUsername, EMError *aError) {
                                               if (!aError) {
                                                   NSLog(@"删除成功");
                                               }
                                           }];

c.获取好友

//从服务器获取所有的好友
[[EMClient sharedClient].contactManager getContactsFromServerWithCompletion:^(NSArray *aList, EMError *aError) {
    if (!aError) {
        NSLog(@"获取成功");
    }
}];
//从数据库获取所有的好友
NSArray *userlist = [[EMClient sharedClient].contactManager getContacts];

构造消息

a.构造文字消息

EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:@"要发送的消息"];
NSString *from = [[EMClient sharedClient] currentUsername];

//生成Message
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"6001" from:from to:@"6001" body:body ext:messageExt];
message.chatType = EMChatTypeChat;// 设置为单聊消息
//message.chatType = EMChatTypeGroupChat;// 设置为群聊消息
//message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息

b.构造图片消息

EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:data displayName:@"image.png"];
NSString *from = [[EMClient sharedClient] currentUsername];

//生成Message
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"6001" from:from to:@"6001" body:body ext:messageExt];
message.chatType = EMChatTypeChat;// 设置为单聊消息
//message.chatType = EMChatTypeGroupChat;// 设置为群聊消息
//message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息

c.构造语音消息

EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:@"audioPath" displayName:@"audio"];
body.duration = duration;
NSString *from = [[EMClient sharedClient] currentUsername];

// 生成message
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"6001" from:from to:@"6001" body:body ext:messageExt];
message.chatType = EMChatTypeChat;// 设置为单聊消息
//message.chatType = EMChatTypeGroupChat;// 设置为群聊消息
//message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息

d.构造视屏消息

EMVideoMessageBody *body = [[EMVideoMessageBody alloc] initWithLocalPath:@"videoPath" displayName:@"video.mp4"];
NSString *from = [[EMClient sharedClient] currentUsername];

// 生成message
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"6001" from:from to:@"6001" body:body ext:messageExt];
message.chatType = EMChatTypeChat;// 设置为单聊消息
//message.chatType = EMChatTypeGroupChat;// 设置为群聊消息
//message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息

e.构造文件消息

EMFileMessageBody *body = [[EMFileMessageBody alloc] initWithLocalPath:@"filePath" displayName:@"file"];
NSString *from = [[EMClient sharedClient] currentUsername];

// 生成message
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"6001" from:from to:@"6001" body:body ext:messageExt];
message.chatType = EMChatTypeChat;// 设置为单聊消息
//message.chatType = EMChatTypeGroupChat;// 设置为群聊消息
//message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息

f.构造透传消息

EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:action];
NSString *from = [[EMClient sharedClient] currentUsername];

// 生成message
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"6001" from:from to:@"6001" body:body ext:messageExt];
message.chatType = EMChatTypeChat;// 设置为单聊消息
//message.chatType = EMChatTypeGroupChat;// 设置为群聊消息
//message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息

会话

a.新建或者获取一个会话

[[EMClient sharedClient].chatManager getConversation:@"8001" type:EMConversationTypeChat createIfNotExist:YES];
//EMConversationTypeChat            单聊会话
//EMConversationTypeGroupChat       群聊会话
//EMConversationTypeChatRoom        聊天室会话

b.删除一个会话

[[EMClient sharedClient].chatManager deleteConversation:@"8001" deleteMessages:YES];

c.获取会话列表

EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:@"8001" type:EMConversationTypeChat createIfNotExist:YES];

d.获取会话未读消息数

[EMConversation unreadMessagesCount];

聊天

a.发送消息

/*!
 @property
 @brief 发送消息
 @discussion
    异步方法
 */
- (void)sendMessage:(EMMessage *)aMessage
           progress:(void (^)(int progress))aProgressBlock
         completion:(void (^)(EMMessage *message, EMError *error))aCompletionBlock;

b.接受消息

//消息回调:EMChatManagerDelegate

//移除消息回调
[[EMClient sharedClient].chatManager removeDelegate:self];

//注册消息回调
[[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
/*!
 @method
 @brief 接收到一条及以上非cmd消息
 */
- (void)didReceiveMessages:(NSArray *)aMessages;

c.解析普通消息

// 收到消息的回调,带有附件类型的消息可以用 SDK 提供的下载附件方法下载(后面会讲到)
- (void)didReceiveMessages:(NSArray *)aMessages
{
    for (EMMessage *message in aMessages) {
    EMMessageBody *msgBody = message.body;
    switch (msgBody.type) {
        case EMMessageBodyTypeText:
        {
            // 收到的文字消息
            EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
            NSString *txt = textBody.text;
            NSLog(@"收到的文字是 txt -- %@",txt);
        }
        break;
        case EMMessageBodyTypeImage:
        {
            // 得到一个图片消息body
            EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
            NSLog(@"大图remote路径 -- %@"   ,body.remotePath);
            NSLog(@"大图local路径 -- %@"    ,body.localPath); // // 需要使用sdk提供的下载方法后才会存在
            NSLog(@"大图的secret -- %@"    ,body.secretKey);
            NSLog(@"大图的W -- %f ,大图的H -- %f",body.size.width,body.size.height);
            NSLog(@"大图的下载状态 -- %lu",body.downloadStatus);


            // 缩略图sdk会自动下载
            NSLog(@"小图remote路径 -- %@"   ,body.thumbnailRemotePath);
            NSLog(@"小图local路径 -- %@"    ,body.thumbnailLocalPath);
            NSLog(@"小图的secret -- %@"    ,body.thumbnailSecretKey);
            NSLog(@"小图的W -- %f ,大图的H -- %f",body.thumbnailSize.width,body.thumbnailSize.height);
            NSLog(@"小图的下载状态 -- %lu",body.thumbnailDownloadStatus);
        }
        break;
        case EMMessageBodyTypeLocation:
        {
            EMLocationMessageBody *body = (EMLocationMessageBody *)msgBody;
            NSLog(@"纬度-- %f",body.latitude);
            NSLog(@"经度-- %f",body.longitude);
            NSLog(@"地址-- %@",body.address);
            }
            break;
        case EMMessageBodyTypeVoice:
        {
            // 音频sdk会自动下载
            EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
            NSLog(@"音频remote路径 -- %@"      ,body.remotePath);
            NSLog(@"音频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在(音频会自动调用)
            NSLog(@"音频的secret -- %@"        ,body.secretKey);
            NSLog(@"音频文件大小 -- %lld"       ,body.fileLength);
            NSLog(@"音频文件的下载状态 -- %lu"   ,body.downloadStatus);
            NSLog(@"音频的时间长度 -- %lu"      ,body.duration);
        }
        break;
        case EMMessageBodyTypeVideo:
        {
            EMVideoMessageBody *body = (EMVideoMessageBody *)msgBody;

            NSLog(@"视频remote路径 -- %@"      ,body.remotePath);
            NSLog(@"视频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
            NSLog(@"视频的secret -- %@"        ,body.secretKey);
            NSLog(@"视频文件大小 -- %lld"       ,body.fileLength);
            NSLog(@"视频文件的下载状态 -- %lu"   ,body.downloadStatus);
            NSLog(@"视频的时间长度 -- %lu"      ,body.duration);
            NSLog(@"视频的W -- %f ,视频的H -- %f", body.thumbnailSize.width, body.thumbnailSize.height);

            // 缩略图sdk会自动下载
            NSLog(@"缩略图的remote路径 -- %@"     ,body.thumbnailRemotePath);
            NSLog(@"缩略图的local路径 -- %@"      ,body.thumbnailLocalPath);
            NSLog(@"缩略图的secret -- %@"        ,body.thumbnailSecretKey);
            NSLog(@"缩略图的下载状态 -- %lu"      ,body.thumbnailDownloadStatus);
        }
        break;
        case EMMessageBodyTypeFile:
        {
            EMFileMessageBody *body = (EMFileMessageBody *)msgBody;
            NSLog(@"文件remote路径 -- %@"      ,body.remotePath);
            NSLog(@"文件local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
            NSLog(@"文件的secret -- %@"        ,body.secretKey);
            NSLog(@"文件文件大小 -- %lld"       ,body.fileLength);
            NSLog(@"文件文件的下载状态 -- %lu"   ,body.downloadStatus);
        }
        break;

        default:
        break;
    }
    }
}

d.解析透传消息

- (void)didReceiveCmdMessages:(NSArray *)aCmdMessages{
    for (EMMessage *message in aCmdMessages) {
        EMCmdMessageBody *body = (EMCmdMessageBody *)message.body;
         NSLog(@"收到的action是 -- %@",body.action);
    }    
}

e.消息已送达回执

/*!
 @method
 @brief 接收到一条及以上已送达回执
 */
- (void)didReceiveHasDeliveredAcks:(NSArray *)aMessages;

f.消息已读回执
发送已读回执

// 发送已读回执。在这里写只是为了演示发送,在APP中具体在哪里发送需要开发者自己决定。
[[EMClient sharedClient].chatManager asyncSendReadAckForMessage:message];

接受已读回执

/*!
 *  接收到一条及以上已读回执
 *
 *  @param aMessages  消息列表
 */
- (void)didReceiveHasReadAcks:(NSArray *)aMessages;

以上方法基本都是在官方文档中可以找到,编写此文章,只为了方便大家随时可以打开,了解具体方法的使用,喜欢的请点个赞,谢谢!!

你可能感兴趣的:(iOS即时通讯-环信API的使用总结)