Swift MQTT with RabbitMQ and LavinMQ

We recommend MQTT NIO, an async/await MQTT client that runs on iOS, macOS and Linux. Add it to your Package.swift:

.package(url: "https://github.com/swift-server-community/mqtt-nio.git", from: "2.13.0"),

Publish and subscribe

Set MQTT_HOST, MQTT_PORT, MQTT_USERNAME and MQTT_PASSWORD to the MQTT details on your instance’s details page in the CloudAMQP console. Port 8883 uses TLS. Without them, the examples connect to a local broker.

Save the publisher as Sources/publisher/Publisher.swift:

import Foundation
import MQTTNIO
import NIOCore
import NIOPosix

@main
struct Publisher {
    static func main() async throws {
        let env = ProcessInfo.processInfo.environment
        let port = Int(env["MQTT_PORT"] ?? "1883")!
        let client = MQTTClient(
            host: env["MQTT_HOST"] ?? "localhost",
            port: port,
            identifier: "publisher-\(UUID())",
            eventLoopGroupProvider: .shared(MultiThreadedEventLoopGroup.singleton),
            configuration: .init(userName: env["MQTT_USERNAME"] ?? "guest", password: env["MQTT_PASSWORD"] ?? "guest", useSSL: port == 8883)
        )
        try await client.connect()

        // QoS 1 returns once the broker has sent its PUBACK
        try await client.publish(to: "hello", payload: ByteBuffer(string: "Hello world!"), qos: .atLeastOnce)
        print(" [x] Sent 'Hello world!'")
        try await client.disconnect()
        try await client.shutdown()
    }
}

Save the subscriber as Sources/worker/Worker.swift:

import Foundation
import MQTTNIO
import NIOCore
import NIOPosix

@main
struct Worker {
    static func main() async throws {
        let env = ProcessInfo.processInfo.environment
        let port = Int(env["MQTT_PORT"] ?? "1883")!
        let client = MQTTClient(
            host: env["MQTT_HOST"] ?? "localhost",
            port: port,
            identifier: "worker-\(UUID())",
            eventLoopGroupProvider: .shared(MultiThreadedEventLoopGroup.singleton),
            configuration: .init(userName: env["MQTT_USERNAME"] ?? "guest", password: env["MQTT_PASSWORD"] ?? "guest", useSSL: port == 8883)
        )
        try await client.connect()

        // Listen before subscribing, so no message is missed
        let listener = client.createPublishListener()
        _ = try await client.subscribe(to: [MQTTSubscribeInfo(topicFilter: "hello", qos: .atLeastOnce)])
        print(" [*] Waiting for messages. To exit press CTRL+C")
        // Flush, so the output shows straight away also when it's piped
        fflush(nil)
        // MQTT NIO acks each QoS 1 message before it is passed on
        for await result in listener {
            print(" [x] Received '\(String(buffer: try result.get().payload))'")
            fflush(nil)
        }
    }
}

Run swift run worker in one terminal and swift run publisher in another. In an iOS app, create the MQTTClient the same way and take the settings from your app’s configuration instead of the environment.

A runnable example is in swift/mqttnio in cloudamqp/examples.

Good to know

  • Put the vhost in the username, as vhost:user. MQTT has no vhost of its own, and the console shows the username that way.
  • useSSL: true verifies the server certificate.
  • Use QoS 1, so publish returns once the broker has sent its PUBACK. MQTT NIO acks each incoming QoS 1 message before passing it to the listener.
  • Keep the publish listener. A listener from createPublishListener() stops receiving once it’s deallocated.
  • MQTT NIO doesn’t reconnect. Add a close listener with addCloseListener, connect again and subscribe again.
Was this page helpful?

Thanks for your feedback!