简体   繁体   English

如何实现URLSessionDelegate允许自签名证书? (式IO / SWIFT)

[英]How to implement URLSessionDelegate to allow self signed certificate? (iOS/Swift)

I'm trying to use SocketIO to connect to a server running on my workstation from an iOS/Swift app. 我正在尝试使用SocketIO从iOS / Swift应用程序连接到在工作站上运行的服务器。 The certificate I'm using on the server is self-signed and I'm using the following code to connect: 我在服务器上使用的证书是自签名的,并且正在使用以下代码进行连接:

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!))
    }

Unfortunately I get the following error: Argument type '(ViewController) -> () -> (ViewController)' does not conform to expected type 'URLSessionDelegate' where I set the sessionDelegate to self. 不幸的是,我收到以下错误:参数类型'(ViewController)->()->(ViewController)'与我将sessionDelegate设置为self的预期类型'URLSessionDelegate'不符。

I'm not sure why that is the case since all funcs in URLSessionDelegate are optional and I thought that my implementation of URLSession conformed to the protocol. 我不确定为什么会这样,因为URLSessionDelegate中的所有功能都是可选的,并且我认为我的URLSession实现符合该协议。 I apologise if I'm doing something dumb but I'm new to iOS and Swift and I've been looking for an answer for hours with no success! 如果我在做一些愚蠢的事情,我感到很抱歉,但是我是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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM