Chapter 8. Advanced MQTT

In Chapters 6 and 7, we used MQTT to send and receive messages from a native iOS application and a web application. MQTT provides additional features that we did not use to write these applications. In this chapter, we will take a tour of all these advanced features provided by MQTT.

This chapter covers the latest version of the protocol at the time of this writing (i.e., MQTT v3.1, which was released on August 19, 2010).

Authentication

In Chapters 6 and 7, we connected to the Eclipse public MQTT broker that accepts unauthenticated connections. We did not need to pass any user credentials, as they would not be checked by the broker anyway.

If you are using an MQTT broker that is configured to accept secured connections, the client needs to pass a username and password when it connects to the broker.

MQTTKit Example

The MQTTClient has two NSString properties that must be set to authenticate the client, username, and password. They must be set prior to calling the client’s connect methods in order to take effect.

If the MQTT broker requires authentication, the client can check if the connection was refused due to invalid user credentials using the ConnectionRefusedBadUserNameOrPassword error code from the completionHandler:

- (void)connect
{
    NSString *username = @"...";
    NSString *password = @"...";

    self.client.username = username;
    self.client.password = password;
    NSLog(@"Connecting to %@...", kMqttHost);
    [self.client connectToHost:kMqttHost
             completionHandler ...

Get Mobile and Web Messaging now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.