首页 > 解决方案 > 如何在 SocketManager 的配置 Swift 上添加 sessionDelegate 选项

问题描述

我正在尝试连接到自签名 SSL URL。但是当我添加 sessionDelegate 作为选项时,它不起作用。

import Foundation
import SocketIO
import UIKit
class SocketM: NSObject, URLSessionDelegate {
    static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config: [.log(true), .secure(true), .selfSigned(true), .sessionDelegate(self)])

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let protectionSpace = challenge.protectionSpace
        guard protectionSpace.authenticationMethod ==
            NSURLAuthenticationMethodServerTrust,
            protectionSpace.host.contains(Services_Routes.host) else {
                completionHandler(.performDefaultHandling, nil)
                return
        }
        guard let serverTrust = protectionSpace.serverTrust else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        let credential = URLCredential(trust: serverTrust)
        completionHandler(.useCredential, credential)
    }

它返回给我类型'Any'没有成员'sessionDelegate'

当我尝试:

SocketIOClientOption.sessionDelegate(self)

类型 '(SocketM) -> () -> SocketM' 不符合协议 'URLSessionDelegate'

有人可以解释我的问题吗?谢谢 !

标签: swiftsocket.iossl-certificateurlsession

解决方案


您正在创建静态变量并将委托作为“self”传递,在初始化对象之前不能使用 self。

如果您不需要管理器的静态对象,那么您可以将代码编写为

class SocketM: NSObject, URLSessionDelegate {
    var manager: SocketManager?

    override init() {
        super.init()
        manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config:  [.log(true), .reconnects(true), .selfSigned(true), .sessionDelegate(self)])
    }
}

如果你想要静态管理器

class SocketM: NSObject, URLSessionDelegate {
    static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config:  [.log(true), .reconnects(true), .selfSigned(true)])

    override init() {
        super.init()
        SocketM.manager.config.insert(.sessionDelegate(self))
    }
}

推荐阅读