SwiftMQTT is an simple MQTT client written on Swift based on MQTT version 3.1.1
- Fully written in Swift 5.2
- Robust error handling
- C performance
- Based on MQTT 3.1.1 Specification
- MacOS support
- tvOS support
- MQTT 5.0 Specification
- Out of the box encryption support
- Documentation
mqttSession = MQTTSession(
host: "localhost",
port: 1883,
clientID: "swift", // must be unique to the client
cleanSession: true,
keepAlive: 15,
useSSL: false
)
mqttSession.connect { error in
if error == .none {
print("Connected!")
} else {
print(error.description)
}
}
let topic = "mytopic"
mqttSession.subscribe(to: topic, delivering: .atLeastOnce) { error in
if error == .none {
print("Subscribed to \(topic)!")
} else {
print(error.description)
}
}
let topic = "mytopic"
mqttSession.unSubscribe(from: topic) { error in
if error == .none {
print("Unsubscribed from \(topic)!")
} else {
print(error.description)
}
}
let json = ["key" : "value"]
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let topic = "mytopic"
mqttSession.publish(data, in: topic, delivering: .atLeastOnce, retain: false) { error in
if error == .none {
print("Published data in \(topic)!")
} else {
print(error.description)
}
}
mqttSession.delegate = self
func mqttDidReceive(message: MQTTMessage, from session: MQTTSession) {
print(message.topic)
print(message.stringRepresentation)
}
func mqttDidDisconnect(session: MQTTSession, error: MQTTSessionError) {
if error == .none {
print("Successfully disconnected from MQTT broker")
} else {
print(error.description)
}
}
Carthage (recommended)
- Install Carthage 0.33.0 or later
- Add
github "anatoliykant/SwiftMQTT"
to your Cartfile - Run
carthage update --platform ios
- Drag SwiftMQTT.framework from the appropriate platform directory in Carthage/Build/ to the “Linked Frameworks and Libraries” section of your Xcode project’s “General” settings
- On your application target’s “Build Phases” settings tab, click the “+” icon and choose “New Run Script Phase”. Create a Run Script with the following contents:
/usr/local/bin/carthage copy-frameworks
and add the paths to the frameworks you want to use under “Input Files”, e.g.:
$(SRCROOT)/Carthage/Build/iOS/SwiftMQTT.framework
This script works around an App Store submission bug triggered by universal binaries.
To integrate SwiftMQTT into your Xcode project using CocoaPods, specify it in your Podfile:
target 'MyApp' do
use_frameworks!
pod 'SwiftMQTT'
end
Once you have your Swift package set up, adding SwiftMQTT as a dependency is as easy as adding it to the dependencies value of your Package.swift:
dependencies: [
.package(url: "https://github.com/anatoliykant/SwiftMQTT.git", from: "3.0.0")
]
SwiftMQTT is released under the MIT license. See LICENSE for details