emqx / CocoaMQTT

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

provide working example #570

Open arikivandeput opened 9 months ago

arikivandeput commented 9 months ago

please provide working example in swiftUI for setting up the client and process the ReceiveMessage i keep getting errors

import Foundation import CocoaMQTT class MQTTManager {

static let shared = MQTTManager()
private init(){

}
func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
    if ack == .accept {
        mqtt.subscribe("bikes", qos: CocoaMQTTQoS.qos1)
    }
}

func setup(){

    let mqtt = CocoaMQTT5(clientID: "iOS_Client", host: "2.tcp.eu.ngrok.io", port: 13963)

    mqtt.connect()
    mqtt.didReceiveMessage = { mqtt, message, id in
        theReturnString = ("Message received in topic (message.topic) with payload (message.string!)")

// mqtt.didConnectAck = { mqtt, ack in // print("Connected: (ack)") // mqtt.subscribe("bikes") // } // // mqtt.didSubscribeTopic = { mqtt, topic, qos in // print("Subscribed to (topic) with QoS (qos)") // } // // mqtt.didReceiveMessage = { mqtt, message, id in // guard let string = message.string else { // print("Received a message but couldn't parse the payload.") // return // } // // print("Message received in topic (message.topic) with payload (string)") // }

// // // The publish can be moved to a more appropriate place after ensuring connection is established // let publishProperties = MqttPublishProperties() // publishProperties.contentType = "JSON" // mqtt.publish("bikes", withString: "from iOS", properties: publishProperties) //

}

}