Connecting to MQTT in Swift & IOS

MQTT is a Message Queuing Telemetry Transport protocol, it is also called MQ Telemetry Transport. It is widely used in IOT (Internet of Things) to have a good connectivity between machine and machines (machine-to-machine M2M). It is designed to be  extremely lightweight to publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. It is widely used in different areas like sensor communications, satellite broker link, dialup connection, healthcare providers and home automations. It is extremely ideal for Mobile Application because of its light weight, low power usage and minimised data packets.. For more information about MQTT visit Here.

I recently had a chance to implement it to one of the smart home application i developed, Therefore i thought of sharing my experience relate  to development. I have implemented this Protocol to my IOS application using Swift programming language.

Instruction to implement MQTT

One of the MQTT library available for IOS is called Moscapsule Visit Here

Lets get started……………..

Add these two lines to your podfile

run the command pod install. Then close and open your .workspace file

Now you have the Moscapules added to you project, open your AppDelegate.swift file and ad the following codes. You can see the comments inside the code itself

Thats it, Its very simple to connect, Since you have implemented this code in you AppDelegate, You can start the connection from anywhere inside the application by calling

You can check connection and subscribe to topics

The best way to send to your view controllers is buy Broadcasting the received message in onMessageCallback . Here is how i have done it.

You can add a broadcast receiver to you ViewController so that you can receive this broadcast

Thats it, Its very simple. Hope this helps for someone.

If you have any Question or suggestions please leave it below in the comments section. Happy Coding 🙂 . Enjoy MQTT

 

I am a Software Engineer.

Leave a Reply

*

Next ArticleSmart Home IOT Project