Skip to content

Swift (iOS) ​

Use CocoaMQTT to connect iOS, iPadOS and macOS apps to ConnectMQ over TLS.

How it connects ​

iOS / macOS app connecting to ConnectMQ A iOS / macOS app uses CocoaMQTT to connect to broker.connectmq.com over MQTT · TLS 8883 with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudMQTT · TLS 8883username · password · client ID <ISSUED_ID>_<suffix>authiOS / macOS appCocoaMQTTmqtt.publish("acme/istanbul/assembly/line1/ipad-01/telemetry", …)iOS, iPadOS and macOS · reconnects automaticallyMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

Install ​

In Xcode, choose File → Add Package Dependencies… and enter:

text
https://github.com/emqx/CocoaMQTT

Publish 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().uuidString is 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 ​

  • CocoaMQTT speaks MQTT 3.1.1; use CocoaMQTT5 for 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/mqtt with CocoaMQTTWebSocket as the socket.
  • Try without an account: connect to broker.connectmq.com on port 1883 without TLS and credentials. The public test broker is readable by anyone, so use it for experiments only.

Fully managed MQTT broker for connected devices.