MQTT通过多个ViewController发送消息

时间:2018-10-06 17:42:19

标签: ios swift uiviewcontroller mqtt

我的mqtt配置有问题。连接正常。 每次我发送一条消息时,切换到另一个ViewController,然后再次按下发送按钮,则树莓派上没有收到消息。 所以问题是,当我切换多个ViewController时,我无法再发送消息了。 我在代码中找不到我的错误:

MQTT-Config的快速文件:

class ConnectionFunctions{
struct staticMQTT {
    static var mqttClient: CocoaMQTT!
}
func configureMQTT() {
    let clientID = "Tablet"
    let host = "192.168.2.106"
    let port = UInt16(1883)
    staticMQTT.mqttClient = CocoaMQTT(clientID: clientID, host: host, port: port)
    staticMQTT.mqttClient.username = ""
    staticMQTT.mqttClient.password = ""
    staticMQTT.mqttClient.keepAlive = 60
    staticMQTT.mqttClient.delegate = self
}
func sendMessage(topic:String, message:String){
    staticMQTT.mqttClient.publish(topic, withString: message)
}

第一视图控制器:

class MainViewController: UIViewController {

//MQTT Setup
var mqttfuncs=ConnectionFunctions()

override func viewDidLoad() {
    super.viewDidLoad()
    mqttfuncs.configureMQTT()
}
    @IBAction func ConnectingButton(_ sender: UIButton) {
    ConnectionFunctions.staticMQTT.mqttClient.connect()
}
@IBAction func Test(_ sender: UIButton) {
    mqttfuncs.sendMessage(topic: "Test", message: "main")
    mqttfuncs.receiveMessage(topic: "Test2")
}

第二个ViewController

class ComponentDataController: UIViewController {
let mqttfuncs = ConnectionFunctions()
    @IBAction func TestSending(_ sender: UIButton) {
    mqttfuncs.sendMessage(topic: "Test", message: "component")
}

使用First View Controller发送可以正常工作,使用第二ViewController发送也可以正常工作,但是当我切换回我的First View Controller并按“发送”按钮时,没有任何反应。

希望您能帮助我! 最好的祝福 克里斯

1 个答案:

答案 0 :(得分:0)

您似乎已尝试将MQTT客户端类设置为单例,但随后的代码看起来有点 off

使用

class MQTTManager {
    static let shared = MQTTManager()

    private var mqttClient: CocoaMQTT

    private init() {
        let clientID = "Tablet"
        let host = "192.168.2.106"
        let port = UInt16(1883)
        self.mqttClient = CocoaMQTT(clientID: clientID, host: host, port: port)
        self.mqttClient.username = ""
        self.mqttClient.password = ""
        self.mqttClient.keepAlive = 60
        self.mqttClient.delegate = self
        self.mqttClient.connect()
    }

    func sendMessage(topic:String, message:String){
        self.mqttClient.publish(topic, withString: message)
    }

    //... other functions which you haven't shown
}

然后发送一条消息,您可以简单地说

MQTTManager.shared.sendMessage(topic:"topic", message:"message")
相关问题