Swift (iOS)
Use CocoaMQTT to connect iOS, iPadOS and macOS apps to ConnectMQ over TLS.
How it connects
Install
In Xcode, choose File → Add Package Dependencies… and enter:
text
https://github.com/emqx/CocoaMQTTPublish and subscribe
swift
import CocoaMQTT
import UIKit
final class TelemetryClient {
private let mqtt: CocoaMQTT
init(issuedClientId: String, username: String, password: String) {
// Issued client ID + "_" + suffix: one suffix per installation
let deviceId = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
mqtt = CocoaMQTT(clientID: "\(issuedClientId)_ios-\(deviceId)",
host: "broker.connectmq.com", port: 8883)
mqtt.username = username
mqtt.password = password
mqtt.enableSSL = true // TLS: the system trust store verifies the broker certificate
mqtt.keepAlive = 60
mqtt.autoReconnect = true // reconnect if the connection drops
// Runs after every (re)connect: subscribe here so subscriptions survive a reconnect
mqtt.didConnectAck = { mqtt, ack in
guard ack == .accept else { print("Refused:", ack); return }
mqtt.subscribe("acme/istanbul/#", qos: .qos1)
}
// Runs for every message on a subscribed topic
mqtt.didReceiveMessage = { _, message, _ in
print(message.topic, message.string ?? "")
}
}
func connect() {
_ = mqtt.connect()
}
func send(temperature: Double) {
mqtt.publish("acme/istanbul/assembly/line1/ipad-01/telemetry",
withString: #"{"temperature":\#(temperature)}"#, qos: .qos1)
}
}Keep one TelemetryClient for the life of the app (for example in your app state), call connect() on launch and send(temperature:) whenever you have a reading.
Client ID and credentials in apps
- A random client ID such as
"ios-" + UUID().uuidStringis refused with Client identifier not valid (0x85). Use your issued client ID plus a suffix that is unique per installation (why). - Credentials shipped inside an app can be extracted. Create a separate credential set for the app and allow it only the topics it needs with access control (ACL).
Notes
CocoaMQTTspeaks MQTT 3.1.1; useCocoaMQTT5for MQTT 5.- iOS suspends network connections in the background. Call
connect()again when the app returns to the foreground if the connection was closed. - If port 8883 is blocked on a network, CocoaMQTT can connect over secure WebSockets:
wss://broker.connectmq.com:8084/mqttwithCocoaMQTTWebSocketas the socket. - Try without an account: connect to
broker.connectmq.comon port 1883 without TLS and credentials. The public test broker is readable by anyone, so use it for experiments only.