I'm trying to send a data from RPI to iOS application the message is showing on the RPI but its not in iOS
//this is the code on RPI
import paho.mqtt.client as MQTT
def connectionStatus(client, userdata, flag, rc):
print("Connecting...")
mqttClient.subscribe("rpi/hello")
def messageDecoder(client, userdata, msg):
message = msg.payload.decode(encoding='UTF-8')
if message == "this is iPhone":
print("Sending reply...")
mqttClient.publish("rpi/world", "this is 3b+")
clientName = "Pi"
serverAddress = "192.168.1.101"
mqttClient = MQTT.Client(clientName)
mqttClient.on_connect = connectionStatus
mqttClient.on_message = messageDecoder
mqttClient.connect(serverAddress)
mqttClient.loop_forever()
here and the code on swift I've tried a lot of ways here can someone please help me solve this problem !
import UIKit
import CocoaMQTT
protocol didReceiveMessageDelegate {
func setMessage(message: String)}
class ViewController: UIViewController {
let mqttClient = CocoaMQTT(clientID: "iOS Device", host: "192.168.1.101", port: 1883)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func connect(_ sender: UIButton) {
mqttClient.connect()
}
@IBAction func disconnect(_ sender: UIButton) {
mqttClient.disconnect()
}
@IBOutlet weak var labelshow: UILabel!
@IBAction func send(_ sender: UIButton) {
mqttClient.publish("rpi/hello", withString: "this is iphone")
mqttClient.subscribe("rpi/world")
}
func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) {
let messageDecoded = String(bytes: message.payload, encoding: .utf8)
print("Did receive a message: \(messageDecoded!)")
}
func setMessage(message: String) {
labelshow.text = message}
}
You need to set your view controller as the MQTT client's delegate
otherwise the didReceiveMessage
delegate function won't be called.
You need to state that your class conforms to CocoaMQTTDelegate
and then assign the delegate
class ViewController: UIViewController, CocoaMQTTDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.mqttClient.delegate = self
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.