title: Swift 3 HTTPS GET Request
body: <p>Hi iam trying to do a get request from a HTTPS url. But iam continously getting the error.</p>
  
  <blockquote>
  <pre><code>2017-10-13 18:13:43.372427+0800 VQ Smart Home[13412:2155414] Unknown class _TtC13VQ_Smart_Home16ManageUserstable in Interface
  </code></pre>
    
    <p>Builder file.
        2017-10-13 18:13:43.403238+0800 VQ Smart Home[13412:2155471] TIC SSL Trust Error [6:0x604000167680]: 3:0
        2017-10-13 18:13:43.403672+0800 VQ Smart Home[13412:2155471] NSURLSession/NSURLConnection HTTP load failed
    (kCFStreamErrorDomainSSL, -9813)
        2017-10-13 18:13:43.404000+0800 VQ Smart Home[13412:2155471] Task &lt;8BB05664-B56E-41CA-92F7-BBAECC8008E3>.&lt;5> HTTP load failed (error
    code: -1202 [3:-9813])
        2017-10-13 18:13:43.404496+0800 VQ Smart Home[13412:2155472] Task &lt;8BB05664-B56E-41CA-92F7-BBAECC8008E3>.&lt;5> finished with error - code:
    -1202
        error=Optional(Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a
    server that is pretending to be “202.73.46.176” which could put your
    confidential information at risk."
    UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to
    connect to the server anyway?, _kCFStreamErrorDomainKey=3,
    _kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey=(
            ""
        ), NSUnderlyingError=0x60400025c920 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)"
    UserInfo={_kCFStreamPropertySSLClientCertificateState=0,
    kCFStreamPropertySSLPeerTrust=,
    _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, kCFStreamPropertySSLPeerCertificates=(
            ""
        )}}, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be
    “202.73.46.176” which could put your confidential information at
    risk.,
    NSErrorFailingURLKey=<a href="https://202.73.46.176/api/v1/user/find/all/1" rel="nofollow noreferrer">https://202.73.46.176/api/v1/user/find/all/1</a>,
    NSErrorFailingURLStringKey=<a href="https://202.73.46.176/api/v1/user/find/all/1" rel="nofollow noreferrer">https://202.73.46.176/api/v1/user/find/all/1</a>,
    NSErrorClientCertificateStateKey=0})</p>
  </blockquote>
  
  <p><strong>ViewdidLoad</strong></p>
  
  <pre><code>let urlstr: String = "https://202.73.46.176/api/v1/user/find/all/1"
  
  let request = NSMutableURLRequest(url: NSURL(string: urlstr)! as URL)
  request.httpMethod = "GET"
  let postString = ""
  request.httpBody = postString.data(using: String.Encoding.utf8)
  
  let task = URLSession.shared.dataTask(with: request as URLRequest) {
      data, response, error in
      if error != nil {
          print("error=\(error)")
          return
      }
      print("response = \(response)")
  
      let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
      print("responseString = \(responseString)")
  }
  task.resume()
  </code></pre>
  
  <p><strong>Method</strong></p>
  
  <pre><code>    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void) {
          //Implementation 1: VERY WEAK METHOD
          /*if challenge.previousFailureCount &gt; 0{
           completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
           }else{
           completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
           }*/
  
          //Implementation 2:
          var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling
          var credential:URLCredential?
  
          if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
              //certificate-based server credentials are used when verifying the server’s identity
              credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
  
              if (credential != nil) {
                  disposition = URLSession.AuthChallengeDisposition.useCredential
              }
              else{
                  disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
              }
          }
          else{
              disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
          }
          print("==============", #function,"  disposition: ", disposition)
          print("==============", #function,"  disposition: ", credential!)
  
          //completionHandler(disposition, credential);
  
  
  
  
          //Implementation 3:
          let serverTrust = challenge.protectionSpace.serverTrust
          let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0)
  
          // Set SSL policies for domain name check
          let policies = NSMutableArray();
          policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)))
          SecTrustSetPolicies(serverTrust!, policies);
  
          // Evaluate server certificate
          var result = SecTrustResultType(rawValue: 0)!
          SecTrustEvaluate(serverTrust!, &amp;result)
  
          let isServerTrusted:Bool = (result == SecTrustResultType.unspecified || result == SecTrustResultType.unspecified || result == SecTrustResultType.proceed)
          print("==============",#function,"  isServerTrusted: ", isServerTrusted)
          print("==============", #function,"  result: ", result.hashValue,"  SecTrustResultType.unspecified: ", SecTrustResultType.unspecified.hashValue,"  SecTrustResultType.proceed: ", SecTrustResultType.proceed.hashValue)
          var certName = ""
  //        if self.isSimulatingCertificateCorruption {
  //            certName = corruptedCert
  //        } else {
  //            certName = cert
  //        }
  
          // Get local and remote cert data
          let remoteCertificateData = SecCertificateCopyData(certificate!) as Data
          let pathToCert            = Bundle.main.path(forResource: certName, ofType: "der")
          let localCertificate      = try! Data(contentsOf: URL(fileURLWithPath: pathToCert!))
          print(" remoteCertificateData: ", remoteCertificateData,"       localCertificate: ", localCertificate, "       serverTrust: ", serverTrust.debugDescription  )
  
          if ( remoteCertificateData == localCertificate) { //TODO:- this is strictly for tesing puposes, to allow untrusted severs. REMOVE IN PRODUCTION.
              let credential:URLCredential = URLCredential(trust: serverTrust!)
              completionHandler(.useCredential, credential)
          }else if (isServerTrusted &amp;&amp; (remoteCertificateData == localCertificate)) {
              let credential:URLCredential = URLCredential(trust: serverTrust!)
              completionHandler(.useCredential, credential)
          } else {
              completionHandler(.cancelAuthenticationChallenge, nil)
          }
      }
  </code></pre>
  
  <p>Can someone help me to fix this tnx.</p>