DMS API FOR IOS
导入静态库
libMQTTKit-dms.a
修改选项
Build Settings 中的 Build Options 里的 Debug Information Format 改为 DWARF
头文件
#import "DMS.h"
初始化客户端对象
DMS * _client;
NSString* clientId = @"IOSTester";
_client = [DMS newWithClientId:clientId];
设置回调代码块
//接受消息的处理代码块
[_client setMessageHandler:^(MQTTMessage *message) {
NSLog(@"%@",message.payloadString);
}];
//断开连接的处理代码块
[_client setDisconnectionHandler:^(NSUInteger code) {
NSLog(@"disconnected");
}];
连接服务器
NSString* address = @"mqttdms.aodianyun.com";
NSString* pubkey = @demo";
NSString* subkey = @"demo";
int result = [_client connectToHost:address
withPubKey:pubkey
subKey:subkey
completionHandler:^(MQTTConnectionReturnCode code) {
if (code == ConnectionAccepted) {
NSLog(@"connected");
} else {
dispatch_async(dispatch_get_main_queue(), ^{
//连接失败后需要断开
[_client disconnectWithCompletionHandler:nil];
NSLog(@"connection refused");
});
}
}];
if(result != DMS_SUCCESS) {
NSLog(@"connection failed");
}
关注话题
NSString* topic = @"test";
[_client subscribe:topic
withCompletionHandler:^(NSArray *grantedQos) {
NSLog(@"%@",[[NSString alloc] initWithFormat:@"%@%@", @"subscribed to topic ",topic]);
}];
推送消息
NSString* payload = @"test message";
NSString* topic = @"test";
[_client publishString:payload
toTopic:topic
completionHandler:^(int mid) {
NSLog(@"published");
}];
取消关注
NSString* topic = @"test";
[_client unsubscribe:topic
withCompletionHandler:^{
NSLog(@"%@",[[NSString alloc] initWithFormat:@"%@%@", @"unsubscribed to topic ",topic]);
}];
断开连接
//当不再需要DMS对象时,务必要断开连接
[_client disconnectWithCompletionHandler:^(NSUInteger code) {
NSLog(@"disconnected");
}];
释放对象
//释放对象前,如果存在连接,请先断开连接,并等待操作完成
//当DMS对象的引用计数为0时,对象将被释放
//以上为开启ARC情况下的示例代码