iOS Develop

MQTTKit使用

2019-09-30  本文已影响0人  iOS_林亦辰

1、 ** MQTTKit ** `已经不更新 但是基本使用没问题

> 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;// 端口号 根据服务端 选择

    self.client = client;

    // 链接MQTT

    [client connectToHost:@"链接的MQTT的URL" completionHandler:^(MQTTConnectionReturnCode code) {

        if (code == ConnectionAccepted) {

            NSLog(@"链接MQTT 成功 😁😁😁");

            // 链接成功  订阅相对应的主题

        [weakSelf.client subscribe:@"你需要订阅的主题" withQos:AtLeastOnce completionHandler:^(NSArray *grantedQos) {

            DLog(@"订阅 返回 %@",grantedQos);

        }];

        }else if (code == ConnectionRefusedBadUserNameOrPassword){

            NSLog(@"MQTT 账号或验证码错误");

        } else if (code == ConnectionRefusedUnacceptableProtocolVersion){

            NSLog(@"MQTT 不可接受的协议");

        }else if (code == ConnectionRefusedIdentiferRejected){

            NSLog(@"MQTT不认可");

        }else if (code == ConnectionRefusedServerUnavailable){

            NSLog(@"MQTT拒绝链接");

        }else {

            NSLog(@"MQTT 未授权");

        }

    }];

// 接收消息体

    client.messageHandler = ^(MQTTMessage *message) {

        NSString *jsonStr = [[NSString alloc] initWithData:message.payload encoding:NSUTF8StringEncoding];

        NSLog(@"EasyMqttService mqtt connect success  %@",jsonStr);

    };

订阅主题


// 方法 封装 可外部调用

-(void)subscribeType:(NSString *)example{

    // 订阅主题

    [self.client subscribe:@"你需要订阅的主题" withQos:AtMostOnce completionHandler:^(NSArray *grantedQos) {

        NSLog(@"订阅 返回 %@",grantedQos);

    }];

}

关闭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:@"已经订阅的主题" withCompletionHandler:^{

            NSLog(@"取消订阅");

        }];

    }];

}

发送消息


  [self.client publishString:postMsg toTopic:@"发送消息的主题 根据服务端定"  withQos:AtLeastOnce retain:NO completionHandler:^(int mid) {

        if (cmd != METHOD_SOCKET_CHAT_TO) {

            NSLog(@"发送消息 返回 %d",mid);

        }

    }];

上一篇 下一篇

猜你喜欢

热点阅读