ios - 如何实现 URLSessionDelegate 以允许自签名证书? (iOS/swift )

标签 ios swift socket.io

我正在尝试使用 SocketIO 从 iOS/Swift 应用程序连接到在我的工作站上运行的服务器。我在服务器上使用的证书是自签名的,我使用以下代码进行连接:

import UIKit
import SocketIO


class ViewController: UIViewController, URLSessionDelegate {
    let socketManager = SocketManager(socketURL: URL(string:"https://my_server_url")!,
                        config: [SocketIOClientOption.log(true),
                                 SocketIOClientOption.forcePolling(true),
                                 SocketIOClientOption.selfSigned(true),
                                 SocketIOClientOption.sessionDelegate(self)])


    func URLSession(_ session: URLSession,
                    task: URLSessionTask,
                    didReceive challenge: URLAuthenticationChallenge,
                    completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?)
        -> Void) {
        print("didReceive challenge")
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }

不幸的是,我收到以下错误:参数类型“(ViewController) -> () -> (ViewController)”不符合我将 sessionDelegate 设置为 self 的预期类型“URLSessionDelegate”。

我不确定为什么会这样,因为 URLSessionDelegate 中的所有函数都是可选的,而且我认为我的 URLSession 实现符合协议(protocol)。如果我在做一些愚蠢的事情,我深表歉意,但我是 iOS 和 Swift 的新手,我一直在寻找几个小时的答案,但没有成功!

最佳答案

func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    // Pass test server with self signed certificate
    if challenge.protectionSpace.host == "self-signed-certificate.server.com" {
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    } else {
        completionHandler(.performDefaultHandling, nil)
    }
}

关于ios - 如何实现 URLSessionDelegate 以允许自签名证书? (iOS/swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833548/

相关文章:

ios - 当新版本的 pod 可用时, `pod update` 会覆盖我的代码更改吗?

ios - 我可以在进入 iBeacon 范围时在前台启动应用程序吗?

javascript - socket.io API 的语法规范

node.js - Socket.io+SailsJS : Chat application-How to check whether the client is shut down, 并使用户离线?

objective-c - 关闭商店 View 后在 App Purchase 中崩溃

ios - 当我实现点击手势识别器时,谷歌地图禁用缩放?

swift - 使用 AVMutableVideoComposition 导出后,纵向视频呈现为横向

如果使用索引,Swift 可以更改用 let 声明的结构,但如果使用循环则不能

Swift 3 - 从核心数据中获取值(value)

javascript - Angular 数组不更新 View