====== 快速使用MQTT iOS版 SDK实现消息收发 ====== 本文介绍快速使用 MQTT iOS版SDK 实现MQTT客户端消息的自收自发。 =====一、前提条件===== ==== 1.部署iOS开发环境 ==== * 下载安装[[https://developer.apple.com/cn/support/xcode|xcode]]。 * 下载安装[[https://www.jianshu.com/p/fb7f533c39fc|cocoapods]],本文以cocoapods为例。 ==== 2.导入项目依赖 ==== 在项目的podfile文件中设置如下: source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' pod 'MQTTClient' pod 'AFNetworking' pod 'MBProgressHUD' pod 'Masonry' pod 'MJRefresh' pod 'YYModel' target 'MQTTChat' do end ===== 二、实现流程 ===== ==== 1.获取鉴权信息 ==== 为保障客户安全性需求,环信MQTT云服务为客户提供【token+clientID】方式实现鉴权认证,其中AppID(clientID中的关键字段)及token标识获取流程如下: === 【登录console】 === 欢迎您登录环信云console控制台,在此控制台中,为您提供应用列表、解决方案、DEMO体验以及常见问题等功能。\\ 在应用列表中,若您未在APP中开通MQTT业务,可参见APP [[http://docs-im.easemob.com/playground/message/msgbusiness|MQTT开通流程]]; 若APP已开通MQTT业务,可在应用列表中选中Appname,点击【查看】操作,进入应用详情。\\ {{:playground:message:msgbusiness_03.jpg|}} === 【获取AppID及连接地址】 === 进入【查看】后,点击左侧菜单栏【MQTT】->【服务概览】,在下图红色方框内获取当前AppID及服务器连接地址。 {{:playground:message:msgbusiness_05.jpg|}} === 【获取token】 === 为实现对用户管控及接入安全性,环信云console提供用户认证功能,支持对用户账户的增、删、改、查以及为每个用户账户分配唯一token标识,获取token标识可选择以下两种形式。\\ 形式一:console控制台获取(管理员视角)\\ * 点击左侧菜单栏【应用概览】->【用户认证】页面,点击【创建IM用户】按钮,增添新的账户信息(包括用户名及密码)。 * 创建成功后,在【用户ID】列表中选中账户,点击【查看token】按钮获取当前账户token信息。 {{:playground:message:qs_01.jpg|}} 形式二:客户端代码获取(客户端视角)\\ * 获取域名:点击左侧菜单栏【即时通讯】->【服务概览】页面,查看下图中token域名、org_name、app_name。 {{:playground:message:qs_02.jpg|}} * 拼接URL:获取token URL格式为:http:/ /token域名/org_name/app_name/token。 \\ * 用户名/密码:使用【用户ID】列表中已有账户的用户名及密码,例“用户名:test/密码:test123”。\\ 客户端获取token代码示例如下: - (void)getTokenWithUsername:(NSString *)username password:(NSString *)password completion:(void (^)(NSString *token))response { NSString *urlString = getToken_url; //初始化一个AFHTTPSessionManager AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //设置请求体数据为json类型 manager.requestSerializer = [AFJSONRequestSerializer serializer]; //设置响应体数据为json类型 manager.responseSerializer = [AFJSONResponseSerializer serializer]; //请求体,参数(NSDictionary 类型) NSDictionary *parameters = @{@"grant_type":@"password", @"username":username, @"password":password }; __block NSString *token = @""; [manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSError *error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&error]; NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; NSLog(@"%s jsonDic:%@",__func__,jsonDic); token = jsonDic[@"access_token"]; response(token); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%s error:%@",__func__,error.debugDescription); response(token); }]; } ==== 2.初始化 ==== 在cocoapods工程中创建MQTT客户端,客户端初始配置包括创建clientID,topic名称,QoS质量,连接地址等信息。 //cientId的生成必须遵循GroupID@@@前缀,且需要保证全局唯一 NSString *deviceID = [UIDevice currentDevice].identifierForVendor.UUIDString; self.clientId = [NSString stringWithFormat:@"%@@@@%@",self.groupId,deviceID]; //初始化manager self.manager = [[MQTTSessionManager alloc] init]; self.manager.delegate = self; //订阅的主题 格式为 xxx/xxx/xxx 可以为多级话题 self.manager.subscriptions = @{[NSString stringWithFormat:@"%@/IOS", self.rootTopic]:@(self.qos),[NSString stringWithFormat:@"%@/IOS_TestToic", self.rootTopic]:@(1)}; ==== 3.连接服务器 ==== 配置连接密码、cleansession标志、心跳间隔、超时时间等信息,调用connect()函数连接至服务器。 //此处从配置文件导入的Host即为MQTT的接入点,该接入点获取方式请参考资源申请章节文档,在控制台上申请MQTT实例,每个实例会分配一个接入点域名 [self.manager connectTo:self.mqttSettings[@"host"] port:[self.mqttSettings[@"port"] intValue] tls:[self.mqttSettings[@"tls"] boolValue] keepalive:60 //心跳间隔不得大于120s clean:true auth:true user:userName pass:token will:false willTopic:nil willMsg:nil willQos:0 willRetainFlag:FALSE withClientId:self.clientId]; ==== 4.订阅(subscribe) ==== === 【订阅主题&取消订阅主题】 === 当客户端成功连接服务器后,通过设置subscriptions参数值实现订阅主题与取消订阅主题 。当subscriptions非空时,订阅主题;当subscriptions为空时,取消订阅主题; /** 订阅主题 格式为 xxx/xxx/xxx 可以为多级话题 @{@"xxx/xxx/xxx...":@(1)} qos定义{ 0: 最多一次,1:至少一次 2:仅一次} */ self.manager.subscriptions = @{[NSString stringWithFormat:@"%@/IOS", self.rootTopic]:@(self.qos),[NSString stringWithFormat:@"%@/IOS_TestToic", self.rootTopic]:@(1)}; /** 取消订阅主题 */ self.manager.subscriptions = @{}; === 【接收消息】 === 接收从服务器接受订阅消息。 /* * MQTTSessionManagerDelegate */ - (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained { /* * MQTTClient: process received message */ NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; [self.receiveMsgs insertObject:[NSString stringWithFormat:@"RecvMsg from Topic: %@ Body: %@", topic, dataString] atIndex:0]; [self.tableView reloadData]; } ==== 5.发布消息(publish) ==== 向指定topic发送消息 - (void)send { /* * MQTTClient: send data to broker */ [self.manager sendData:[self.messageTextField.text dataUsingEncoding:NSUTF8StringEncoding] topic:[NSString stringWithFormat:@"%@/%@", self.rootTopic, @"IOS"]//此处设置多级子topic qos:self.qos retain:FALSE]; } ==== 6.断开连接 ==== MQTT client发送断开连接请求。 /* * 断开连接 */ - (void)disConnect { [self.manager disconnect]; self.manager.subscriptions = @{}; } ==== 7.重新连接 ==== MQTT client发送重新连接请求。 /* * 重新连接 */ - (void)connect { [self.manager connectToLast]; } ===== 三、更多信息 ===== * 完整demo示例,请参见[[https://github.com/jinliang04551/MQTTChatDemo.git|demo下载]]。 * 目前MQTT客户端支持多种语言,请参见 [[http://docs-im.easemob.com/playground/message/sdkdownload|SDK下载]]。 * 如果您在使用MQTT服务中,有任何疑问和建议,欢迎您[[http://docs-im.easemob.com/playground/message/msgcontact|联系我们]]。