emqx / CocoaMQTT

MQTT 5.0 client library for iOS and macOS written in Swift
https://www.emqx.com/en
Other
1.59k stars 418 forks source link

How To Connect MQTT #377

Closed altayeng closed 2 years ago

altayeng commented 3 years ago

I want to make simple MQTT Subscribe app for iOS. User press button and data's will show in the screen. So i decided to install CocoaMQTT. Before to design main screen, i'll connect to my mqtt with viewcontroller.swift for show datas in terminal menu at XCode. Here is my code:

`

import UIKit import CocoaMQTT

class ViewController: UIViewController { var mqtt: CocoaMQTT?

override func viewDidLoad() {
    mqttSetting()
    super.viewDidLoad()
       }

func mqttSetting() {
        let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
        let mqtt = CocoaMQTT(clientID: clientID, host:  "broker.mqttdashboard.com", port: 8000)
        mqtt.username = ""
        mqtt.password = ""
       print(mqtt.willMessage = CocoaMQTTWill(topic: "/test/1", message: "dieout"))
        mqtt.keepAlive = 60
     //   mqtt.delegate = self
        mqtt.connect()

        mqtt.didReceiveMessage = { mqtt, message, id in
            print("Message received in topic \(message.topic) with payload \(message.string!)")
}
}

} `

After i build this code, nothing happening. Meanwhile, mqtt.delegate is give me a error. How can i connect to my mqtt and sub it? Thanks for help.

leeway1208 commented 2 years ago

First of all, you should make sure your broker is working. Then try to use the connection function:

   mqtt = CocoaMQTT(clientID: "mqttdashboard", host: "broker.mqttdashboard.com", port: 8000)
   mqtt!.username = ""
   mqtt!.password = ""
   mqtt!.willMessage = CocoaMQTTMessage(topic: "your topic", string: "dieout")
   mqtt!.keepAlive = 60
   mqtt!.delegate = self

If the connection is accept, you will get the delegate from mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck). After that you can use mqtt.subscribe("your topic", qos: CocoaMQTTQoS.qos1) to make new subscription


    func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
        if ack == .accept {
            mqtt.subscribe("your topic", qos: CocoaMQTTQoS.qos1)
        }
    }
SudharsanK58 commented 1 year ago

Cannot find 'mqtt' in scope