【问题标题】:How to implement URLSessionDelegate to allow self signed certificate? (iOS/Swift)如何实现 URLSessionDelegate 以允许自签名证书? (iOS/斯威夫特)
【发布时间】:2018-02-16 19:24:37
【问题描述】:

我正在尝试使用 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)”不符合预期的类型“URLSessionDelegate”,我将 sessionDelegate 设置为 self。

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

【问题讨论】:

    标签: ios swift socket.io


    【解决方案1】:
    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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2023-03-17
      • 1970-01-01
      • 2014-08-13
      • 2017-07-22
      • 2017-03-24
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多