title: The certificate is invalid when connecting iOS app to an api running on localhost with Alamofire
body: <p>I'm trying to connect to an API running on localhost so I can test out my app in the iOS emulator. I'm getting</p>
  
  <blockquote>
    <p>NSLocalizedDescription=The certificate for this server is invalid. 
        You might be connecting to a server that is pretending to be “127.0.0.1” 
        which could put your confidential information at risk., 
        NSErrorFailingURLKey=<a href="https://127.0.0.1:8000/post/" rel="nofollow noreferrer">https://127.0.0.1:8000/post/</a>, 
        NSErrorFailingURLStringKey=<a href="https://127.0.0.1:8000/post/" rel="nofollow noreferrer">https://127.0.0.1:8000/post/</a>, 
        NSErrorClientCertificateStateKey=0</p>
  </blockquote>
  
  <p>I'm using <strong>Alamofire</strong>. <a href="https://stackoverflow.com/questions/30163274/how-to-connect-localhost-with-invalid-certificate-using-alamofire">This similar question</a> has not helped. It seems to be outdated from an older version of Alamofire.</p>
  
  <p>My info.plist already contains</p>
  
  <pre><code>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt;
  &lt;dict&gt;
      &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt;
      &lt;true/&gt;
  &lt;/dict&gt;
  </code></pre>
  
  <p>How can I temporarily disable the certificate requirement so I can test my app on localhost?</p>
  
  <p>Here is my code after changing the server trust policies as was suggested in one of the answers</p>
  
  <p>ViewController:</p>
  
  <pre><code>class TableViewController: UIViewController {
      let postClient = PostServiceClient.sharedInstance
  
      override func viewDidLoad() {
          super.viewDidLoad()
          postClient.getPosts()
      }
  }
  </code></pre>
  
  <p>PostServiceClient:</p>
  
  <pre><code>import Alamofire
  
  class PostServiceClient {
  
      static let sharedInstance: PostServiceClient = PostServiceClient()
  
      var sessionManager : SessionManager!
  
      init() {
          let serverTrustPolicies: [String: ServerTrustPolicy] = [
              "https://127.0.0.1:8000/" : .disableEvaluation
          ]
  
          self.sessionManager =  SessionManager(configuration: URLSessionConfiguration.default,
                                                serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
          )
      }
      static let url = URL.init(string: "https://127.0.0.1:8000/post/")
  
      // Method to get posts from the wall
      func getPosts(){
          print("Getting posts with completion handler")
          var request = URLRequest(url: PostServiceClient.url!)
          request.httpMethod = "GET"
          self.sessionManager.request(request).responseJSON { (response) in
              guard response.result.isSuccess else {
                  print("Error while getting posts: \(String(describing: response.result.error))")
                  return
              }
              guard let responseJSON = response.result.value as? [String: Any],
                  let results = responseJSON["results"] as? [[String: Any]] else {
                  print("Invalid response recieved from service")
                  return
              }
              print(responseJSON)
          }
  
      }
  }
  </code></pre>
  
  <p>Here is the full output I'm getting:</p>
  
  <blockquote>
    <p>Getting posts with completion handler 2017-06-19 14:22:15.770616-0400
    WallAppiOS[28605:9092279] []
    nw_coretls_callback_handshake_message_block_invoke_3
    tls_handshake_continue: [-9812] 2017-06-19 14:22:15.770
    WallAppiOS[28605:9092321] NSURLSession/NSURLConnection HTTP load
    failed (kCFStreamErrorDomainSSL, -9813) Error while getting posts:
    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 “127.0.0.1” which could put your confidential
    information at risk." UserInfo={NSLocalizedDescription=The certificate
    for this server is invalid. You might be connecting to a server that
    is pretending to be “127.0.0.1” which could put your confidential
    information at risk., NSLocalizedRecoverySuggestion=Would you like to
    connect to the server anyway?, _kCFStreamErrorDomainKey=3,
    NSUnderlyingError=0x7a3627c0 {Error Domain=kCFErrorDomainCFNetwork
    Code=-1202 "(null)"
    UserInfo={_kCFStreamPropertySSLClientCertificateState=0,
    _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorCodeKey=-9813, _kCFStreamErrorDomainKey=3, kCFStreamPropertySSLPeerTrust=,
    kCFStreamPropertySSLPeerCertificates=(
        "" )}}, _kCFStreamErrorCodeKey=-9813, NSErrorFailingURLStringKey=<a href="https://127.0.0.1:8000/post/" rel="nofollow noreferrer">https://127.0.0.1:8000/post/</a>,
    NSErrorPeerCertificateChainKey=(
        "" ), NSErrorClientCertificateStateKey=0,
    NSURLErrorFailingURLPeerTrustErrorKey=,
    NSErrorFailingURLKey=<a href="https://127.0.0.1:8000/post/" rel="nofollow noreferrer">https://127.0.0.1:8000/post/</a>})</p>
  </blockquote>