1、 ** MQTTKit ** `已經(jīng)不更新 但是基本使用沒問題
> pod 'MQTTKit'
頭文件
> #import <MQTTKit.h>
#define WEAKSELF __typeof(&*self) __weak weakSelf = self;
@property (nonatomic, strong) MQTTClient *client;
初始化 鏈接
WEAKSELF
NSString *clientID = @"測試client - 必須是全局唯一的id ";
MQTTClient *client = [[MQTTClient alloc] initWithClientId:StrFormat(@"%@", clientID)];
client.username = @"username";
client.password = @"password";
client.cleanSession = false;
client.keepAlive = 20;
client.port = 11883;// 端口號 根據(jù)服務(wù)端 選擇
self.client = client;
// 鏈接MQTT
[client connectToHost:@"鏈接的MQTT的URL" completionHandler:^(MQTTConnectionReturnCode code) {
if (code == ConnectionAccepted) {
NSLog(@"鏈接MQTT 成功 ??????");
// 鏈接成功 訂閱相對應(yīng)的主題
[weakSelf.client subscribe:@"你需要訂閱的主題" withQos:AtLeastOnce completionHandler:^(NSArray *grantedQos) {
DLog(@"訂閱 返回 %@",grantedQos);
}];
}else if (code == ConnectionRefusedBadUserNameOrPassword){
NSLog(@"MQTT 賬號或驗證碼錯誤");
} else if (code == ConnectionRefusedUnacceptableProtocolVersion){
NSLog(@"MQTT 不可接受的協(xié)議");
}else if (code == ConnectionRefusedIdentiferRejected){
NSLog(@"MQTT不認(rèn)可");
}else if (code == ConnectionRefusedServerUnavailable){
NSLog(@"MQTT拒絕鏈接");
}else {
NSLog(@"MQTT 未授權(quán)");
}
}];
// 接收消息體
client.messageHandler = ^(MQTTMessage *message) {
NSString *jsonStr = [[NSString alloc] initWithData:message.payload encoding:NSUTF8StringEncoding];
NSLog(@"EasyMqttService mqtt connect success %@",jsonStr);
};
訂閱主題
// 方法 封裝 可外部調(diào)用
-(void)subscribeType:(NSString *)example{
// 訂閱主題
[self.client subscribe:@"你需要訂閱的主題" withQos:AtMostOnce completionHandler:^(NSArray *grantedQos) {
NSLog(@"訂閱 返回 %@",grantedQos);
}];
}
關(guān)閉MQTTKit
-(void)closeMQTTClient{
WEAKSELF
[self.client disconnectWithCompletionHandler:^(NSUInteger code) {
// The client is disconnected when this completion handler is called
NSLog(@"MQTT client is disconnected");
[weakSelf.client unsubscribe:@"已經(jīng)訂閱的主題" withCompletionHandler:^{
NSLog(@"取消訂閱");
}];
}];
}
發(fā)送消息
[self.client publishString:postMsg toTopic:@"發(fā)送消息的主題 根據(jù)服務(wù)端定" withQos:AtLeastOnce retain:NO completionHandler:^(int mid) {
if (cmd != METHOD_SOCKET_CHAT_TO) {
NSLog(@"發(fā)送消息 返回 %d",mid);
}
}];