Last month I was trying to use Mqtt for the 1st time in one of my app. As a beginner, it was very difficult for me to find out how and where to put sample codes that I found in various sources.
After spending a week on my problem, I managed to make mqtt work in my project, so here I am to share what I learned steps by steps. This is not really a question (xD!)
First of all, let give the credits to the developer(s) of Moscapsule. You can find more info and details on their github page.
Okay, let's start the show.
How to implement mqtt client with Moscapsule on iOS (Swift)?
1) use pod to install Moscapsule (check here again).
2) in your viewcontroller file (or whatever name you use xxxx.swift):
a) import Moscapusle
b) before viewDidLoad () method, configure and create the mqtt client (make it a global variable).
//set MQTT client configuration
let mqttConfig = MQTTConfig(clientId: "iOS_test_mqtt", host: "yourserver.adress.com", port: 1883, keepAlive: 60)
// create new MQTT Connection
var mqttClient: MQTTClient? = nil
3) in the viewDidLoad() or in another method where you need it, please implement the onPublish method and the onMessageCallback method.
mqttConfig.onPublishCallback = { messageId in
print("published (msg id=\(messageId)))")
}
mqttConfig.onMessageCallback = { mqttMessage in
print("MQTT Message received: payload=\(mqttMessage.payloadString)")
let receivedMessage = mqttMessage.payloadString!
print("from server msg = \(receivedMessage)")
let data = receivedMessage.data(using: .utf8, allowLossyConversion: false)!
print("xxxxxxx = \(data)")
}
4) Get, read and manipulate the received messages inside the mqttConfig.onMessageCallback = { }. Here is an example on how I read a qrCode key (inside a json) received from my mqtt server through a mqtt request
mqttConfig.onMessageCallback = { mqttMessage in
print("MQTT Message received: payload=\(mqttMessage.payloadString)")
let receivedMessage = mqttMessage.payloadString!
print("from server msg = \(receivedMessage)")
let data = receivedMessage.data(using: .utf8, allowLossyConversion: false)!
print("xxxxxxx = \(data)")
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
/*
* catch and analyse the contents of the received messages from the differents request
*/
// message received from the qrCode creation request
if let randomKey = json["jsonanswer"]?.value(forKey: "randomkey"){
print("the random key is = \(randomKey)")
}
5) do not forget to establish the mqtt connection of the client you created. Use this code example
mqttClient = MQTT.newConnection(mqttConfig, connectImmediately: true)
6) Also you need to subscribe to the topic(s) you want to listen. use this code example
mqttClient?.subscribe("opencampus/getqr/\(myUserUniqueID)", qos: 0)
7) if you want to publish something (a message) to a topic when an action is performed (e.g: user clicked a button) put the following code in your btnPressd func. Refer to this code example
@IBAction func btnGenerateQRCodePressed(_ sender: UIButton) {
// publish the user unique ID when user click the button
print("###### unique id = \(myUserUniqueID)")
mqttClient?.publish(string: "{\"uniqueid\": \"\(myUserUniqueID)\"}", topic: "opencampus/generateqr", qos: 0, retain: false)
}
8) last thing to do, is to disconnect your mqtt client when you finish to use it.
self.mqttClient?.disconnect()
Voila!!!! Everything should work fine for you if your mqtt server is well configured and connected.
I am not really good at explaining things, but let me know if something wrong happens when you try!!! Sharing is the key, so let's work together!!!!