---
title: "Swift / Kotlin MQTT Example: Connect, Publish and Subscribe | ConnectMQ"
description: "Swift / Kotlin MQTT client example with CocoaMQTT (iOS) · HiveMQ MQTT Client (Android): copy-paste code for the free public broker broker.connectmq.com and a secure TLS connection to ConnectMQ."
url: "https://connectmq.com/code-samples/swift-kotlin/"
language: "en"
---

Code samples

# Swift / Kotlin MQTT example

Connect native iOS (Swift) and Android (Kotlin) apps to an MQTT broker. Start on the free public broker, then point the same code at a secure private broker on ConnectMQ.

Library

[CocoaMQTT (iOS) · HiveMQ MQTT Client (Android)](https://github.com/emqx/CocoaMQTT)

Install

`# iOS (Swift Package Manager): https://github.com/emqx/CocoaMQTT # Android (Gradle): implementation("com.hivemq:hivemq-mqtt-client:1.3.3")`

[**Source code on GitHub**`mqtt-code-samples/swift-kotlin`Clone the complete, runnable examples. Stars and pull requests welcome. View on GitHub](https://github.com/connectmq/mqtt-code-samples/tree/main/swift-kotlin)

## 1\. Try it on the free public broker

No account needed: connect to `broker.connectmq.com` on port 1883 and start publishing in seconds.

Swift (CocoaMQTT)

```
import CocoaMQTT

let topic = "your-project/sensors/temperature" // Use a unique topic prefix: everyone can read the public broker

// Connect to the free public broker (no account needed) (Every client needs a unique client ID)
let mqtt = CocoaMQTT(clientID: "ios-" + UUID().uuidString, host: "broker.connectmq.com", port: 1883)
mqtt.keepAlive = 30

// Runs when the connection is established
mqtt.didConnectAck = { mqtt, _ in
    // Subscribe to the temperature topic
    mqtt.subscribe(topic, qos: .qos1)
    // Publish a JSON reading
    mqtt.publish(topic, withString: #"{"temperature":21.5}"#, qos: .qos1)
}
// Runs for every message on a subscribed topic
mqtt.didReceiveMessage = { _, message, _ in
    print(message.topic, message.string ?? "")
}
_ = mqtt.connect()
```

Kotlin (HiveMQ MQTT Client)

```
import com.hivemq.client.mqtt.MqttGlobalPublishFilter
import com.hivemq.client.mqtt.datatypes.MqttQos
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client
import java.util.UUID

fun main() {
    val topic = "your-project/sensors/temperature" // Use a unique topic prefix: everyone can read the public broker

    // Connect to the free public broker (no account needed) (Every client needs a unique client ID)
    val client = Mqtt5Client.builder()
        .identifier("android-" + UUID.randomUUID())
        .serverHost("broker.connectmq.com")
        .serverPort(1883)
        .automaticReconnectWithDefaultConfig()
        .buildBlocking()
    client.connect()

    // Runs for every message on a subscribed topic
    client.toAsync().publishes(MqttGlobalPublishFilter.ALL) { p ->
        println("${p.topic}: ${String(p.payloadAsBytes)}")
    }
    // Subscribe to the temperature topic
    client.subscribeWith().topicFilter(topic).qos(MqttQos.AT_LEAST_ONCE).send()
    // Publish a JSON reading
    client.publishWith().topic(topic).qos(MqttQos.AT_LEAST_ONCE)
        .payload("""{"temperature":21.5}""".toByteArray()).send()
}
```

### Free public MQTT broker

The public broker is shared: anyone can subscribe to your topics. Never send passwords, personal data or anything confidential through it.

[About the free public MQTT broker](https://connectmq.com/public-mqtt-broker/)

## 2\. Go to production with ConnectMQ

For real devices, use a private serverless MQTT broker on ConnectMQ instead of the public one: TLS encryption, a username and password for every device and per-topic access control, fully managed. Start on the Free plan — no card required.

Replace YOUR\_BROKER\_HOST, YOUR\_USERNAME and YOUR\_PASSWORD with the values from your ConnectMQ dashboard.

[Start for free](https://app.connectmq.com/signup) [See pricing](https://connectmq.com/pricing/)

Swift (CocoaMQTT)

```
import CocoaMQTT

let topic = "your-project/sensors/temperature"

// Connect to your private ConnectMQ broker on port 8883 (Every client needs a unique client ID)
let mqtt = CocoaMQTT(clientID: "ios-" + UUID().uuidString, host: "YOUR_BROKER_HOST", port: 8883)
mqtt.keepAlive = 30
// Username and password from your ConnectMQ dashboard
mqtt.username = "YOUR_USERNAME"
mqtt.password = "YOUR_PASSWORD"
// TLS: the system CA store verifies the broker certificate
mqtt.enableSSL = true

// Runs when the connection is established
mqtt.didConnectAck = { mqtt, _ in
    // Subscribe to the temperature topic
    mqtt.subscribe(topic, qos: .qos1)
    // Publish a JSON reading
    mqtt.publish(topic, withString: #"{"temperature":21.5}"#, qos: .qos1)
}
// Runs for every message on a subscribed topic
mqtt.didReceiveMessage = { _, message, _ in
    print(message.topic, message.string ?? "")
}
_ = mqtt.connect()
```

Kotlin (HiveMQ MQTT Client)

```
import com.hivemq.client.mqtt.MqttGlobalPublishFilter
import com.hivemq.client.mqtt.datatypes.MqttQos
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client
import java.util.UUID

fun main() {
    val topic = "your-project/sensors/temperature"

    // Connect to your private ConnectMQ broker on port 8883 (Every client needs a unique client ID)
    val client = Mqtt5Client.builder()
        .identifier("android-" + UUID.randomUUID())
        .serverHost("YOUR_BROKER_HOST")
        .serverPort(8883)
        // TLS: the system CA store verifies the broker certificate
        .sslWithDefaultConfig()
        // Username and password from your ConnectMQ dashboard
        .simpleAuth().username("YOUR_USERNAME").password("YOUR_PASSWORD".toByteArray()).applySimpleAuth()
        .automaticReconnectWithDefaultConfig()
        .buildBlocking()
    client.connect()

    // Runs for every message on a subscribed topic
    client.toAsync().publishes(MqttGlobalPublishFilter.ALL) { p ->
        println("${p.topic}: ${String(p.payloadAsBytes)}")
    }
    // Subscribe to the temperature topic
    client.subscribeWith().topicFilter(topic).qos(MqttQos.AT_LEAST_ONCE).send()
    // Publish a JSON reading
    client.publishWith().topic(topic).qos(MqttQos.AT_LEAST_ONCE)
        .payload("""{"temperature":21.5}""".toByteArray()).send()
}
```

## Swift / Kotlin MQTT FAQ

How do I connect Swift / Kotlin to an MQTT broker?

Install CocoaMQTT (iOS) · HiveMQ MQTT Client (Android), connect to the broker host on port 1883 (or 8883 with TLS), then subscribe to a topic and publish messages to it. The examples on this page connect to the free public broker broker.connectmq.com and to a private ConnectMQ broker.

Is there a free MQTT broker for testing Swift / Kotlin?

Yes. broker.connectmq.com is a free public MQTT broker that needs no account. Anyone can read its topics, so use it only for tests and use a unique topic prefix.

How do I secure a Swift / Kotlin MQTT connection?

Connect over TLS on port 8883 with a username and password from your ConnectMQ dashboard, and give every device its own credentials and topic permissions instead of using the public broker.

## More code samples

[

### Python

Connect Python to an MQTT broker with paho-mqtt.

View example](https://connectmq.com/code-samples/python/)[

### Node.js

Connect Node.js to an MQTT broker with MQTT.js.

View example](https://connectmq.com/code-samples/nodejs/)[

### ESP32

Connect an ESP32 to an MQTT broker over Wi-Fi with the Arduino PubSubClient library.

View example](https://connectmq.com/code-samples/esp32/)[

### Go

Connect Go to an MQTT broker with the Eclipse Paho Go client.

View example](https://connectmq.com/code-samples/go/)[

### CLI (mosquitto)

Publish and subscribe from the command line with mosquitto\_pub and mosquitto\_sub.

View example](https://connectmq.com/code-samples/cli/)[

### Java

Connect Java to an MQTT broker with the Eclipse Paho Java client.

View example](https://connectmq.com/code-samples/java/)[

### C# (.NET)

Connect C# and .NET to an MQTT broker with MQTTnet.

View example](https://connectmq.com/code-samples/csharp/)[

### Rust

Connect Rust to an MQTT broker with the rumqttc crate.

View example](https://connectmq.com/code-samples/rust/)[

### Dart (Flutter)

Connect Dart and Flutter apps to an MQTT broker with the mqtt\_client package.

View example](https://connectmq.com/code-samples/dart-flutter/)[

### Home Assistant

Connect Home Assistant to an MQTT broker and turn MQTT messages into sensors.

View example](https://connectmq.com/code-samples/home-assistant/)[

### Node-RED

Connect Node-RED to an MQTT broker with an importable flow.

View example](https://connectmq.com/code-samples/node-red/)

[All code samples](https://connectmq.com/code-samples/)

### Free public MQTT broker

Test any example on broker.connectmq.com — no sign-up, MQTT 3.1.1 and 5, TCP, TLS and WebSocket.

[About the free public MQTT broker](https://connectmq.com/public-mqtt-broker/)

### Secure serverless MQTT for production

When it is time for real devices, run the same code on a private, fully managed ConnectMQ broker with TLS and per-device credentials.

[Start for free](https://app.connectmq.com/signup)

## Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.

[Get started](https://app.connectmq.com/signup) [See pricing](https://connectmq.com/pricing/)

## Articles

[All articles](https://connectmq.com/blog/)

IoT Tutorials

### [ESP32 MQTT Tutorial: Publish Sensor Data and Control an LED with Arduino IDE](https://connectmq.com/blog/esp32-mqtt-tutorial/)

Connect an ESP32 to an MQTT broker with Arduino IDE and PubSubClient, publish JSON temperature readings, control the onboard LED from the command line and upgrade to TLS with portal credentials.

August 23, 20269 min read

IoT Tutorials

### [Free Public MQTT Broker for Testing: Connect to broker.connectmq.com in Minutes](https://connectmq.com/blog/free-public-mqtt-broker/)

broker.connectmq.com is a free public MQTT broker for testing and learning. Here are the ports, the anonymous access rules, the limits and copy-paste examples for the CLI, Python, Node.js and the browser.

September 20, 20267 min read

IoT Tutorials

### [MQTT over WebSocket: Connect a Browser to an MQTT Broker with MQTT.js](https://connectmq.com/blog/mqtt-over-websocket/)

Browsers cannot open raw TCP sockets, so web apps speak MQTT over WebSocket. Build a working browser client and a Node.js client against broker.connectmq.com and learn how to fix the most common connection errors.

September 29, 20268 min read
