swift - 如何在 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'
有人可以解释我的问题吗?谢谢 !
解决方案
您正在创建静态变量并将委托作为“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))
}
}
推荐阅读
- javafx - 我可以对 JavaFX 工具提示的一部分进行样式化吗?
- python-3.x - Visual Studio 包 Python
- java - 如何在准备好的语句查询中使用 oracle SYSTIMESTAMP?
- python - 为什么python中socket的accept方法无法退出
- json - 如何使用 AWS 胶水获取存储在 s3 中的模式或已处理的嵌套 json 文件压缩(gzip)?
- node.js - 重置 Sequelize 数据库
- python - 我的神经网络模型准确率始终为 50%
- c# - C#更改数据网格视图的特定行字体
- sql - Bigquery - 窗口函数 - 过去 3 个月的总和
- python - 如何从python中的csv中提取列