gpt4 book ai didi

ios - 在ios中使用mosquitto api实现Swift MQTT协议(protocol)

转载 作者:行者123 更新时间:2023-11-29 05:11:41 24 4
gpt4 key购买 nike

我正在尝试使用 mosquitto api 实现 MQTT 协议(protocol)来进行实时位置更新。我已经设置了本地服务器,并且在终端消息中发送和接收良好,但在我的项目中不发送。这是我的代码。我正在分享终端屏幕简短内容。

enter image description here

import UIKit
import CocoaMQTT



func mqttSetUp()
{
let clientID = "mosq-irTRTw6KH28CzBbUPC" //+ "tutzqscv"//String(ProcessInfo().processIdentifier)
let mqtt = CocoaMQTT(clientID: clientID, host: "/usr/local/etc/mosquitto/mosquitto.conf", port: 1883)
mqtt.username = "p2"
mqtt.password = "c1"
mqtt.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
mqtt.keepAlive = 60
mqtt.delegate = self
mqtt.disconnect()
mqtt.connect()
}

func TRACE(_ message: String = "", fun: String = #function) {
let names = fun.components(separatedBy: ":")
var prettyName: String
if names.count == 2 {
prettyName = names[0]
} else {
prettyName = names[1]
}

if fun == "mqttDidDisconnect(_:withError:)" {
prettyName = "didDisconect"
}
print("[TRACE] [\(prettyName)]: \(message)")
}
}
extension ViewController: CocoaMQTTDelegate
{
func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopic topic: String)
{
print("topic==>\(topic)")
}


// Optional ssl CocoaMQTTDelegate
func mqtt(_ mqtt: CocoaMQTT, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
TRACE("trust: \(trust)")

completionHandler(true)
}

func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
TRACE("ack: \(ack)")

if ack == .accept {
mqtt.subscribe("chat/room/animals/client/+", qos: CocoaMQTTQOS.qos1)
}
}

func mqtt(_ mqtt: CocoaMQTT, didStateChangeTo state: CocoaMQTTConnState) {
TRACE("new state: \(state)")
}

func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
TRACE("message: \(message.string!.description), id: \(id)")
}

func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
TRACE("id: \(id)")
}

func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) {
TRACE("message: \(message.string!.description), id: \(id)")

let name = NSNotification.Name(rawValue: "MQTTMessageNotification")
NotificationCenter.default.post(name: name, object: self, userInfo: ["message": message.string!, "topic": message.topic])
}

func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopics success: NSDictionary, failed: [String]) {
TRACE("subscribed: \(success), failed: \(failed)")
}

func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopic topics: [String]) {
TRACE("topic: \(topics)")
}

func mqttDidPing(_ mqtt: CocoaMQTT) {
TRACE()
}

func mqttDidReceivePong(_ mqtt: CocoaMQTT) {
TRACE()
}

func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) {
TRACE("\(err.debugDescription)")
}
}

最佳答案

创建 Mqtt Siglton 类

import UIKit
import CocoaMQTT

class MQTT {

var objMQTTClient : CocoaMQTT?

static let shared = MQTT()
private init() {}
}

请创建dicPayload用于MQTT传递

func publishMQTTMessage() {

var dicPayload = [String : Any]()
dicPayload["sender_id"] = <Pass Sender Id>
dicPayload["recv_id"] = <Pass reciver Id>
dicPayload["message"] = <message>
dicPayload["chat_type"] = <userChatType>
dicPayload["message_type"] = <messageType>

MQTT.shared.MQTTPublishWithTopic(dicPayload, appDelegate.loginUser.userId, CMQTTUSERTOPIC)

}

使用 MQTT 主题发布消息

func MQTTPublishWithTopic(_ payload:[String : Any], _ id:Any?, _ topic : String?)
{
let jsonData = try? JSONSerialization.data(withJSONObject: payload, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)
objMQTTClient?.publish(topic!, withString: jsonString!)
print("message publish")

}

关于ios - 在ios中使用mosquitto api实现Swift MQTT协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59623538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com