NextMQTT is a modern MQTT 5.0 client for iOS and watchOS.
It currently includes basic functionality including subscribe/ unsubscribe and publish/ receive with "at most once" (QoS 0) delivery.
Although the project is actively maintained, it is not yet production-ready and contributions are welcome.
Closures may be called on a background thread. Always dispatch to main before updating UI from a NextMQTTT closure.
Create
mqtt = MQTT(host: "127.0.0.1", port: 1883)
// or
mqtt = MQTT(host: "my.mqttserver.com", port: 1883, username: "myuser", password: "mypassword", options: [
.secureConnection: true,
.pingInterval: 10,
.clientId: "myclientid",
.maxBuffer: 16384
])
Connect
mqtt.connect { result in
switch result {
case .success():
print("connected")
case .failure(let error):
print(error.description)
}
}
Subscribe
let filter = "mytopics/#"
mqtt.subscribe(to: filter) { result in
switch result {
case .success():
print("subscribed")
case .failure(let error):
print(error.description)
}
}
Unsubscribe
let filter = "mytopics/#"
mqtt.unSubscribe(from: filter) { result in
switch result {
case .success():
print("unsubscribed")
case .failure(let error):
print(error.description)
}
}
Publish
let jsonMessage = ["key" : "value"]
let encodedMessage = try! JSONEncoder().encode(json)
let topic = "mytopics/atopic"
mqtt.publish(to: topic, data: encodedMessage)
Receive
mqtt.onReceive = { topic, encodedMessage in
print("received publish from \(topic)")
if let data = encodedMessage, let message = try? JSONDecoder().decode(Message.self, from: data) {
print(message)
}
}
Monitor
mqtt.onConnectionState = { state in
print("new connection state is \(state)")
}
In your Xcode project, select File > Swift Packages > Add Package Dependency... and add https://github.com/followben/NextMQTT
. For the latest stable changes, select the master
branch.
NextMQTT has been tested on watchOS 6 and iOS 13. In theory NextMQTT will also work on macOS 12 and tvOS but this hasn't been verified.
PRs are welcome. For major changes, open an issue first to discuss what you would like to change.
Please ensure tests pass and are up-to-date.
Planned features include:
- Support for QoS 1 and 2 incl. session state
- Properties, incl. User Properties
- Publish with retain
- Will Messages
- Extended authentication flows
There is currently no plan to support MQTT 3.1, Websockets or Shared Subscriptions.
This project is licensed under the MIT License - see the LICENSE.md file for details