/MQTTKit

MQTT Objective-C client for iOS / Support TLS/SSL

Primary LanguageCApache License 2.0Apache-2.0

MQTTKit

MQTTKit is a modern event-driven Objective-C library for MQTT 3.1.

It uses Mosquitto 1.2.3 library.

Usage

Import the MQTTKit.h header file

#import <MQTTKit.h>

Send a Message

// create the client with a unique client ID
NSString *clientID = ...
MQTTClient *client = [[MQTTClient alloc] initWithClientId:clientID];

// connect to the MQTT server
[self.client connectToHost:@"iot.eclipse.org" 
         completionHandler:^(NSUInteger code) {
    if (code == ConnectionAccepted) {
        // when the client is connected, send a MQTT message
        [self.client publishString:@"Hello, MQTT"
                           toTopic:@"/MQTTKit/example"
                           withQos:AtMostOnce
                            retain:NO
                 completionHandler:^(int mid) {
            NSLog(@"message has been delivered");
        }];
    }
}];

Subscribe to a Topic and Receive Messages

// define the handler that will be called when MQTT messages are received by the client
[self.client setMessageHandler:^(MQTTMessage *message) {
    NSString *text = [message.payloadString];
    NSLog(@"received message %@", text);
}];

// connect the MQTT client
[self.client connectToHost:@"iot.eclipse.org"
         completionHandler:^(MQTTConnectionReturnCode code) {
    if (code == ConnectionAccepted) {
        // when the client is connected, subscribe to the topic to receive message.
        [self.client subscribe:@"/MQTTKit/example"
         withCompletionHandler:nil];
    }
}];

Disconnect from the server

[self.client disconnectWithCompletionHandler:^(NSUInteger code) {
    // The client is disconnected when this completion handler is called
    NSLog(@"MQTT client is disconnected");
}];

TLS/SSL support

Mosquitto support TLS/SSL by OpenSSL but it's removed in iOS. So you need compile OpenSSL for iOS Devices (iPhone, iPad, iPod Touch, AppleTV) by yurself. -> OpenSSL-for-iPhone

  • One way authentication
self.client.tlsCafile = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"crt"];
    
[self.client connectWithCompletionHandler:^(MQTTConnectionReturnCode code) {
    if (code == 0)
    {
        NSLog(@"Connect Success");
    }
    else
    {
        NSLog(@"Connect Fail! State Code is %lu", (unsigned long)code);
    }
}];
  • Mutual authentication
client.tlsCerPath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"crt"];
client.tlsCerKeyPath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"key"];
client.tlsCafile = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"crt"];
client.tlsPeerCertVerify = YES;
client.tlsInsecure = true;
    
[client connectWithCompletionHandler:^(MQTTConnectionReturnCode code) {
    if (code == 0)
    {
        NSLog(@"Connect Success");
    }
    else
    {
        NSLog(@"Connect Fail! State Code is %lu", (unsigned long)code);
    }
}];

Authors