When accessing the HTTPS server, you can use the local HTTPS server with a self-signed certificate, which facilitates application debugging.

Apple already requires HTTPS in iOS 9. If the HTTPS server is a CA-signed certificate, then all the way is green, and if it is a self-signed certificate, two additional work needs to be done:

  1. In the info. In the plist join a NSAppTransportSecurity | NSAllowsArbitraryLoads keywords, can indicate the arbitrary loading content
    <key>NSAppTransportSecurity</key>
     <dict>
         <key>NSAllowsArbitraryLoads</key>
         <true/>
     </dict>Copy the code
  2. The trust server certificate is specified through the URLSessionDelegate

The code is as follows:

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!))
    }
}Copy the code

The node.js server code follows the code in the section “Creating HTTPS and HTTP servers”. After execution, the output should be:

json: {
    foo = bar;
}Copy the code