Non-blocking, event-driven Swift client for MQTT (5.0 and 3.1.1) build on SwiftNIO.
This library has support for WebSocket connections and TLS. It runs on all platforms Swift NIO runs on (e.g. macOS, iOS, Linux, etc.).
Use the SPM string to easily include the dependendency in your Package.swift file.
.package(url: "https://github.com/sroebert/mqtt-nio.git", from: "2.0.0")
MQTTNIO supports the following platforms:
- Ubuntu 18.04+
- macOS 10.9+, iOS 7+, tvOS 12+ or watchOS 6+
This package has four dependencies:
apple/swift-nio
for IO.apple/swift-nio-ssl
for TLS.apple/swift-nio-transport-services
to support Apple platforms as first-class citizens.apple/swift-log
for logging.
This package has no additional system dependencies.
let client = MQTTClient(
configuration: .init(
target: .host("127.0.0.1", port: 1883)
),
eventLoopGroupProvider: .createNew
)
client.connect()
The client automatically reconnects when failing to connect or when disconnected from the broker.
let client = MQTTClient(
configuration: .init(
target: .host("127.0.0.1", port: 1883),
protocolVersion: .version3_1_1
),
eventLoopGroupProvider: .createNew
)
client.connect()
let client = MQTTClient(configuration: .init(url: URL(string: "mqtts://test.mosquitto.org")!))
client.connect()
let client = MQTTClient(configuration: .init(url: URL(string: "wss://test.mosquitto.org:8081")!))
client.connect()
client.subscribe(to: "some/topic")
client.unsubscribe(from: "some/topic")
client.publish("Hello World!", to: "some/topic", qos: .exactlyOnce)
client.publish("Hello World!", "some/topic")
client.publish("Hello World!", to: "some/topic", retain: true)
client.whenConnected { response in
print("Connected, is session present: \(response.isSessionPresent)")
}
client.whenDisconnected { reason in
print("Disconnected: \(reason)")
}
client.whenMessage { message in
print("Received: \(message)")
}
For platforms where the Combine
framework is available, it is also possible to subscribe to publishers.
let cancellable = client.connectPublisher
.sink { response in
print("Connected, is session present: \(response.isSessionPresent)")
}
let cancellable = client.disconnectPublisher
.sink { reason in
print("Disconnected: \(reason)")
}
let cancellable1 = client.messagePublisher
.sink { message in
print("Received: \(message)")
}
let cancellable2 = client.messagePublisher(forTopic: "some/topic")
.sink { message in
print("Received: \(message)")
}
On platforms where async await is supported, it is possible to use async functions on MQTTClient
.
try await client.publish("Hello World!", "some/topic")
for await message in client.messages {
print("Received: \(message)")
}
To easily run the tests locally, first generate self signed certificates followed by running docker-compose to setup the needed MQTT broker containers.
./mosquitto/certs/generate.sh
docker compose up