Привязка открытого ключа в Swift 2

Я могу установить HTTP-соединение с сервером, используя следующую функцию.

func isHostConnected(jsonString:NSDictionary, var retryCounter: Int) -> NSDictionary
{

    let request = NSMutableURLRequest(URL: NSURL(string: "http://***.*.*.**:****/")!)

    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
    } catch {
        //error = error1
        request.HTTPBody = nil
    }
    request.timeoutInterval = 45.0 //(number as! NSTimeInterval)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")

    var JSONdata: AnyObject = ["" : ""] as Dictionary<String, String>
    //print(JSONdata)

    if retryCounter == 0 {
        JSONdata = ["0" : "0"] as Dictionary<String, String>
        return (JSONdata) as! NSDictionary
    }
    retryCounter--

    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    var responseCode = -1

    let group = dispatch_group_create()
    dispatch_group_enter(group)

    print("session.dataTaskWithRequest")
    delayTimer(1.0){

        session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            if let httpResponse = response as? NSHTTPURLResponse {
                responseCode = httpResponse.statusCode
                let JSONresdata: AnyObject = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers))
                JSONdata = JSONresdata as! NSDictionary
            }
            dispatch_group_leave(group)
        }).resume()
    }

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
    print("responseCode == 200: \(responseCode)")
    if responseCode != 200 {
        print("retryCounter: \(retryCounter)")
        self.isHostConnected(jsonString,retryCounter: retryCounter)
    }
    return (JSONdata) as! NSDictionary
}

Теперь в той же функции мы хотим установить соединение HTTPS, где у меня есть самоподписанный сертификат. Я хочу знать, для реализации закрепления открытого ключа, какие шаги мне нужно выполнить с моим самоподписанным сертификатом с написанием фрагмента кода.

Я искал в Интернете, но не нашел ни одного примера или фрагмента кода для этого в NSURLSession и swift 2. Пожалуйста, помогите мне с этим.


person Amit Raj    schedule 28.09.2015    source источник
comment
Здесь уже есть ответ о том, как это сделать на SO, я думаю: stackoverflow.com/questions/34223291/   -  person WaterNotWords    schedule 10.02.2016


Ответы (1)


Может оказаться полезным следующий код: ссылка

 import UIKit
 import Foundation
 class ViewController: UIViewController, NSURLSessionDelegate {

     override func viewDidLoad() {
          super.viewDidLoad()
         httpGet(NSMutableURLRequest(URL: NSURL(string: "https://example.com")!))
     }

    func httpGet(request: NSMutableURLRequest!) {


        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in


       }).resume()
   }


  func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
   completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
  }

}
person Karlos    schedule 29.09.2015