Swift iOS : 访问自签名证书https服务器

访问HTTPS服务器时,可以使用自签名证书的、在本地的https服务器,对于调试应用是非常方便的。

Apple已经在iOS 9版本要求必须使用https。如果https服务器是CA签署的证书,那么一路绿灯,如果是自签名证书,就需要做两个额外的工作:

  1. 在info.plist内加入一个NSAppTransportSecurity|NSAllowsArbitraryLoads关键字,指明可以任意加载内容
    <key>NSAppTransportSecurity</key>
     <dict>
         <key>NSAllowsArbitraryLoads</key>
         <true/>
     </dict>复制代码
  2. 通过URLSessionDelegate,指明信任服务器证书

代码如下:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,URLSessionDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        foo()
        return true
    }
    lazy var ss : URLSession  = {

        let config = URLSessionConfiguration.default
        let session = Foundation.URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
        return session

    }()
    func foo(){
        let urlString = URL(string: "https://localhost:8000")
        if let url = urlString {
            let task = ss.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print(error)
                } else {
                    if let usableData = data {
                        //                        print(usableData) //JSONSerialization
                        do {
                            let json = try JSONSerialization.jsonObject(with: usableData, options:[])
                            print("json: \(json)")
                        }
                        catch {
                            print("Error: \(error)")
                        }
                    }
                }
            }
            task.resume()
        }
    }
    public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)
    {
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }
}复制代码

node.js服务器代码采用“创建https和http服务器”一节的代码。执行后,输出应该是:

json: {
    foo = bar;
}复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值