CloudAMQP with MQTT and Swift

Recommende library for Swift is Moscapsule.

This example show how to connect to the MQTT Broker. The ClientId is the unique MQTT client id to use for the device.

import Moscapsule

// set MQTT Client Configuration
let mqttConfig = MQTTConfig(clientId: "client_cid", host: "host", port: port, keepAlive: 60)

mqttConfig.mqttAuthOpts = MQTTAuthOpts(username: "username", password: "password")

mqttConfig.onPublishCallback = { messageId in
  NSLog("published (mid=\(messageId))")
}
mqttConfig.onMessageCallback = { mqttMessage in
  NSLog("MQTT Message received: payload=\(mqttMessage.payloadString)")
}

// create new MQTT Connection
let mqttClient = MQTT.newConnection(mqttConfig)

// publish and subscribe
mqttClient.publishString("Hello CloudAMQP MQTT", topic: "topic", qos: 2, retain: false)
mqttClient.subscribe("topic", qos: 2)

// disconnect
mqttClient.disconnect()