ios - MQTT 通过多个 ViewController 发送消息

标签 ios swift uiviewcontroller mqtt

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

MQTT 配置的 Swift 文件:

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)
}

第一个 View Controller :

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")
}

第二个 View Controller

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

使用第一个 View Controller 发送工作正常,在使用第二个 View Controller 发送之后也工作正常,但是当我切换回我的第一个 View Controller 并按下发送按钮时没有任何反应。

希望你能帮助我! 此致 克里斯

最佳答案

您似乎尝试将 MQTT 客户端类设置为单例,但代码看起来有点不对

使用

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")

关于ios - MQTT 通过多个 ViewController 发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52681710/

相关文章:

.net - 用于 MonoTouch 的 Log4Net

ios - UITableViewCell 对齐列以适应内容

uiviewcontroller - tvOS 中的presentControllerWithName

iPhone如何检查对象的类型?

iOS越狱设备开发: How to dump method calls

iphone - 使用 json 文件折叠展开标题部分

ios - Facebook 网络对话框中的预填充数据

ios - 设置框架未正确调整 UIView 的大小

ios - SQLite WHERE 列 MATCH 参数绑定(bind)

iphone - IOS。 viewControllers 数组的错误?