美文网首页MQTT
iOS MQTT SDK - CocoaMQTT 介绍

iOS MQTT SDK - CocoaMQTT 介绍

作者: EMQ | 来源:发表于2018-07-22 22:47 被阅读139次

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 连接

  • 单向认证
    mqtt!.enableSSL = true
    
    // 信任所有不可信的 CA 证书,根据实际情况确定是否添加
    mqtt.allowUntrustCACertificate = true
    
  • 双向认证

    需要先生成一个 .p12 文件,可以用如下命令生成,生成后拖入 Xcode 里

    $ openssl pkcs12 -export -clcerts -in client-cert.pem -inkey client-key.pem -out client.p12
    

    示例代码

    mqtt!.enableSSL = true
    let clientCertArray = getClientCertFromP12File(certName: "client-keycert", certPassword: "MySecretPassword")
    var sslSettings: [String: NSObject] = [:]
    
    // clientCertArray 请见 Example/Example.xcworkspace
    sslSettings[kCFStreamSSLCertificates as String] = clientCertArray
    mqtt!.sslSettings = sslSettings
    

    如果客户端需要验证服务器证书

    func mqtt(_ mqtt: CocoaMQTT, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
        TRACE("trust: \(trust)")
        /// Validate the server certificate
        ///
        /// Some custom validation...
        ///
        /// if validatePassed {
        ///     completionHandler(true)
        /// } else {
        ///     completionHandler(false)
        /// }
        completionHandler(true)
    }
    

相关文章

网友评论

  • 帆动世界:客户端需要验证服务器证书 怎么验证呢

本文标题:iOS MQTT SDK - CocoaMQTT 介绍

本文链接:https://www.haomeiwen.com/subject/edgrmftx.html