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

swiftUI mqtt delegate #444

Closed kwalkerk closed 2 years ago

kwalkerk commented 2 years ago

I'm building an app using swiftUI which needs to use CocoaMQTT.

Here's the function I'm using:

` func showMQTT()->String{ ///MQTT 3.1.1 var theReturnString="" let clientID = ""

let mqtt = CocoaMQTT(clientID: clientID, host: "localhost", port: 1883)

// mqtt.username = "test" //mqtt.password = "public" mqtt.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout") mqtt.keepAlive = 60 mqtt.delegate = self mqtt.connect() mqtt.didReceiveMessage = { mqtt, message, id in theReturnString = ("Message received in topic (message.topic) with payload (message.string!)")

}

return theReturnString

} `

I can't get that to compile - I get this message on the mqtt.delegate= self line: Cannot find 'self' in scope

Any ideas?

kwalkerk commented 2 years ago

Found a fix

In ContentView @State var theMessage = "test text" let mqttClient = CocoaMQTT(clientID: "", host: "10.0.1.32", port: 1883) let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

Then in the VStack: ` Text(theMessage) .onReceive(timer) { _ in

                    self.mqttClient.didConnectAck = { mqtt, ack in
                       self.mqttClient.subscribe("weather/davis")
                       self.mqttClient.didReceiveMessage = { mqtt, message, id in
                          print("\(message.string!)")
                           self.theMessage = ("\(message.string!)")
                       }
                    }
                    //self.mqttClient.username="user"
                    self.mqttClient.keepAlive=60
                    print("status")
                    if(self.mqttClient.connState == .connected){
                        print("connected")
                    } else {
                        print("disconnected")
                        self.mqttClient.connect()
                    }
                    self.Connection.toggle()

                }
            .font(.system(size:140,weight:.medium,design: .default))
            .foregroundColor(.black)
            .padding()

`