SocketIOClient:处理事件:数据错误:[“无效的SSL证书”]

时间:2018-06-21 05:11:55

标签: swift ssl websocket socket.io ssl-certificate

问题与无效的SSL Certificate有关。我一直在尝试使用Websocket连接到SocketIOClient。但是出现无效的SSL证书问题。用于连接Socket的代码是

import UIKit
import SocketIO
class SocketIOManager: NSObject, URLSessionDelegate {

    static let shared = SocketIOManager()
    var socket: SocketIOClient!

    func socketConnect() {

        let token = "ggggggg" //some token
        let url  = URL(string: "https://sample.com") // some https url
        let specs: SocketIOClientConfiguration = [
            .connectParams(["access_token": token]),
            .log(true),
            .forceNew(true),
            .selfSigned(true),
            .forcePolling(true),
            .secure(true),
            .reconnects(true),
            .forceWebsockets(true),
            .reconnectAttempts(3),
            .reconnectWait(3),
            .security(SSLSecurity(usePublicKeys: true)),
            .sessionDelegate(self),
            ]
        socket = SocketIOClient(socketURL: url!, config: specs)

        socket.on(clientEvent: .connect) {data, ack in
            print("socket connected")
            self.socket.emitWithAck("emit", with: []).timingOut(after: 2, callback: { (data) in
                print(data)
            })
        }

        socket.on("fetch") { (dataArray, ack) in
            print(dataArray)
        }

        socket.on(clientEvent: .error) {data, ack in
            print(data)
        }

        socket.on(clientEvent: .disconnect) {data, ack in
            print(data)
        }

        socket.onAny { (data) in
            // print(data)
        }

        socket.connect()

    }

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }

    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
        // We've got an error
        if let err = error {
            print("Error: \(err.localizedDescription)")
        } else {
            print("Error. Giving up")
        }
    }

}

1 个答案:

答案 0 :(得分:0)

有两种可能的解决方法

解决方案1:

只需在主捆绑包中添加所需的ssl证书(.cer文件)即可。就是这样!

解决方案2:

*如果不需要自签名和SSL固定,则可以修改代码规范,例如下面的代码。

let specs: SocketIOClientConfiguration = [
        .connectParams(["access_token": token]),
        .log(true),
        .forceNew(true),
        .forcePolling(true),
        .reconnects(true),
        .forceWebsockets(true),
        .reconnectAttempts(3),
        .reconnectWait(3),
        .sessionDelegate(self),
        ]