MQTT

iOS MQTT SDK - CocoaMQTT 介绍

2018-07-22  本文已影响139人  EMQ

CocoaMQTT 是一款由EMQ开发提供的 iOS/macOS/tvOS 下的 开源 MQTT 客户端库, 使用 Swift 4.0 编写,完整支持 MQTT v3.1.1 协议。

安装

CocoaPods

添加以下两行代码到实际项目的 Podfile 文件里

se_frameworks! # Add this if you are targeting iOS 8+ or using Swift
pod 'CocoaMQTT'

然后在终端运行以下命令

$ pod install

Carthage

添加以下代码到实际项目的 Cartfile 文件里

github "robbiehanson/CocoaAsyncSocket" "master"
github "radex/SwiftyTimer" "master"
github "emqtt/CocoaMQTT" "master"

然后在终端运行以下命令

$ carthage update --platform iOS

使用

详细使用样例请参考 Example/Example.xcworkspace

客户端属性、方法

protocol CocoaMQTTClient {
    var host: String { get set }
    var port: UInt16 { get set }
    var clientID: String { get }
    var username: String? {get set}
    var password: String? {get set}
    var cleanSession: Bool {get set}
    var keepAlive: UInt16 {get set}
    var willMessage: CocoaMQTTWill? {get set}

    func connect() -> Bool
    func disconnect()
    func ping()
    
    func subscribe(_ topic: String, qos: CocoaMQTTQOS) -> UInt16
    func unsubscribe(_ topic: String) -> UInt16
    func publish(_ topic: String, withString string: String, qos: CocoaMQTTQOS, retained: Bool, dup: Bool) -> UInt16
    func publish(_ message: CocoaMQTTMessage) -> UInt16
}

普通 TCP 连接

连接

let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
mqtt = CocoaMQTT(clientID: clientID, host: defaultHost, port: 1883)
mqtt!.username = "test"
mqtt!.password = "public"
mqtt!.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
mqtt!.keepAlive = 60
mqtt!.delegate = self
mqtt!.connect()

消息接收

extension ViewController: CocoaMQTTDelegate {
    func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) {
        print("Message received in topic \(message.topic) with payload \(message.string!)")
    }
}

也可以使用闭包的方式接收消息

mqtt.didReceiveMessage = { mqtt, message, id in
    print("Message received in topic \(message.topic) with payload \(message.string!)")           
}

SSL 连接

上一篇下一篇

猜你喜欢

热点阅读