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

1,940 阅读1分钟

访问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;
}