Connect to a Server with Invalid Certificate using NSURLSession (swift2,xcode7,ios9)












3















I'm using Xcode 7, Swift 2, and iOS9. I want to connect to a web service using NSURLSession but I get the following error when I try to connect:



2015-10-13 16:07:33.595 XCTRunner[89220:4520715] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2015-10-13 16:07:33.604 XCTRunner[89220:4520571] Error with connection, details: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “domainapi.com” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x7fac7b6facc0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?,


Here is my code:



func request( dataPost : String, successHandler: (response: String) -> Void)-> String {
let destination:String = "https://domainapi.com:8743/WebService/sendData"
let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
NSLog("Body is: %@", request.HTTPBody!)
NSLog("Request is: %@", request.allHTTPHeaderFields!)
NSLog("URL is: %@", destination)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in


if error != nil {
NSLog("Error with connection, details: %@", error!)
return
}

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

successHandler(response: responseString as String!);
NSLog("Data received: %@", data!)

}

task.resume()
return "worked"
}
func viewDidLoad() {
let dataPost : String = "<webservices>xml data sending</webservices>"
request(dataPost, successHandler: {
(response) in
let text = response
print(text)
});


I've looked into NSURLAuthenticationChallenge but I can't seem to figure that out with the code I currently have in place. So my question is how can I connect to the server anyway? I've already tried adding the domain to my NSAppTransportSecurity in Info.plist but that did not work. Turning on NSAllowsArbitraryLoads didn't work either. Any help would be appreciated.










share|improve this question




















  • 1





    Check out this question on SO: stackoverflow.com/questions/933331/…

    – Code Different
    Oct 14 '15 at 14:38











  • @ZoffDino that's using NSURLConnection which is deprecated in iOS8. I'd like to use NSURLSession if possible.

    – cakes88
    Oct 14 '15 at 14:40






  • 1





    The AFNetworking library has excellent support for this, I would recommend checking it out.

    – Jacob King
    Oct 14 '15 at 16:02
















3















I'm using Xcode 7, Swift 2, and iOS9. I want to connect to a web service using NSURLSession but I get the following error when I try to connect:



2015-10-13 16:07:33.595 XCTRunner[89220:4520715] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2015-10-13 16:07:33.604 XCTRunner[89220:4520571] Error with connection, details: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “domainapi.com” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x7fac7b6facc0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?,


Here is my code:



func request( dataPost : String, successHandler: (response: String) -> Void)-> String {
let destination:String = "https://domainapi.com:8743/WebService/sendData"
let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
NSLog("Body is: %@", request.HTTPBody!)
NSLog("Request is: %@", request.allHTTPHeaderFields!)
NSLog("URL is: %@", destination)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in


if error != nil {
NSLog("Error with connection, details: %@", error!)
return
}

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

successHandler(response: responseString as String!);
NSLog("Data received: %@", data!)

}

task.resume()
return "worked"
}
func viewDidLoad() {
let dataPost : String = "<webservices>xml data sending</webservices>"
request(dataPost, successHandler: {
(response) in
let text = response
print(text)
});


I've looked into NSURLAuthenticationChallenge but I can't seem to figure that out with the code I currently have in place. So my question is how can I connect to the server anyway? I've already tried adding the domain to my NSAppTransportSecurity in Info.plist but that did not work. Turning on NSAllowsArbitraryLoads didn't work either. Any help would be appreciated.










share|improve this question




















  • 1





    Check out this question on SO: stackoverflow.com/questions/933331/…

    – Code Different
    Oct 14 '15 at 14:38











  • @ZoffDino that's using NSURLConnection which is deprecated in iOS8. I'd like to use NSURLSession if possible.

    – cakes88
    Oct 14 '15 at 14:40






  • 1





    The AFNetworking library has excellent support for this, I would recommend checking it out.

    – Jacob King
    Oct 14 '15 at 16:02














3












3








3


1






I'm using Xcode 7, Swift 2, and iOS9. I want to connect to a web service using NSURLSession but I get the following error when I try to connect:



2015-10-13 16:07:33.595 XCTRunner[89220:4520715] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2015-10-13 16:07:33.604 XCTRunner[89220:4520571] Error with connection, details: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “domainapi.com” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x7fac7b6facc0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?,


Here is my code:



func request( dataPost : String, successHandler: (response: String) -> Void)-> String {
let destination:String = "https://domainapi.com:8743/WebService/sendData"
let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
NSLog("Body is: %@", request.HTTPBody!)
NSLog("Request is: %@", request.allHTTPHeaderFields!)
NSLog("URL is: %@", destination)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in


if error != nil {
NSLog("Error with connection, details: %@", error!)
return
}

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

successHandler(response: responseString as String!);
NSLog("Data received: %@", data!)

}

task.resume()
return "worked"
}
func viewDidLoad() {
let dataPost : String = "<webservices>xml data sending</webservices>"
request(dataPost, successHandler: {
(response) in
let text = response
print(text)
});


I've looked into NSURLAuthenticationChallenge but I can't seem to figure that out with the code I currently have in place. So my question is how can I connect to the server anyway? I've already tried adding the domain to my NSAppTransportSecurity in Info.plist but that did not work. Turning on NSAllowsArbitraryLoads didn't work either. Any help would be appreciated.










share|improve this question
















I'm using Xcode 7, Swift 2, and iOS9. I want to connect to a web service using NSURLSession but I get the following error when I try to connect:



2015-10-13 16:07:33.595 XCTRunner[89220:4520715] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2015-10-13 16:07:33.604 XCTRunner[89220:4520571] Error with connection, details: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “domainapi.com” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x7fac7b6facc0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?,


Here is my code:



func request( dataPost : String, successHandler: (response: String) -> Void)-> String {
let destination:String = "https://domainapi.com:8743/WebService/sendData"
let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
NSLog("Body is: %@", request.HTTPBody!)
NSLog("Request is: %@", request.allHTTPHeaderFields!)
NSLog("URL is: %@", destination)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in


if error != nil {
NSLog("Error with connection, details: %@", error!)
return
}

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

successHandler(response: responseString as String!);
NSLog("Data received: %@", data!)

}

task.resume()
return "worked"
}
func viewDidLoad() {
let dataPost : String = "<webservices>xml data sending</webservices>"
request(dataPost, successHandler: {
(response) in
let text = response
print(text)
});


I've looked into NSURLAuthenticationChallenge but I can't seem to figure that out with the code I currently have in place. So my question is how can I connect to the server anyway? I've already tried adding the domain to my NSAppTransportSecurity in Info.plist but that did not work. Turning on NSAllowsArbitraryLoads didn't work either. Any help would be appreciated.







xcode swift swift2 ios9 xcode7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 14 '15 at 16:11









Charles Truluck

525424




525424










asked Oct 14 '15 at 14:33









cakes88cakes88

1,00621731




1,00621731








  • 1





    Check out this question on SO: stackoverflow.com/questions/933331/…

    – Code Different
    Oct 14 '15 at 14:38











  • @ZoffDino that's using NSURLConnection which is deprecated in iOS8. I'd like to use NSURLSession if possible.

    – cakes88
    Oct 14 '15 at 14:40






  • 1





    The AFNetworking library has excellent support for this, I would recommend checking it out.

    – Jacob King
    Oct 14 '15 at 16:02














  • 1





    Check out this question on SO: stackoverflow.com/questions/933331/…

    – Code Different
    Oct 14 '15 at 14:38











  • @ZoffDino that's using NSURLConnection which is deprecated in iOS8. I'd like to use NSURLSession if possible.

    – cakes88
    Oct 14 '15 at 14:40






  • 1





    The AFNetworking library has excellent support for this, I would recommend checking it out.

    – Jacob King
    Oct 14 '15 at 16:02








1




1





Check out this question on SO: stackoverflow.com/questions/933331/…

– Code Different
Oct 14 '15 at 14:38





Check out this question on SO: stackoverflow.com/questions/933331/…

– Code Different
Oct 14 '15 at 14:38













@ZoffDino that's using NSURLConnection which is deprecated in iOS8. I'd like to use NSURLSession if possible.

– cakes88
Oct 14 '15 at 14:40





@ZoffDino that's using NSURLConnection which is deprecated in iOS8. I'd like to use NSURLSession if possible.

– cakes88
Oct 14 '15 at 14:40




1




1





The AFNetworking library has excellent support for this, I would recommend checking it out.

– Jacob King
Oct 14 '15 at 16:02





The AFNetworking library has excellent support for this, I would recommend checking it out.

– Jacob King
Oct 14 '15 at 16:02












4 Answers
4






active

oldest

votes


















10














Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.



You'll most likely need the delegate method of the form,



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


Adding this to my own comms class that uses NSURLSession fixed the issue.






share|improve this answer


























  • It really works for me.

    – DawnSong
    Nov 12 '16 at 8:19






  • 1





    i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

    – Sumit
    Dec 2 '16 at 12:22



















4














When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:



let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)


Then, implement the following delegate method, it should work.



func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}


However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.






share|improve this answer































    0














    open your info.plist as a source code
    Add following:



        <key>NSAppTransportSecurity</key>
    <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    </dict>


    This should help.






    share|improve this answer



















    • 1





      I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

      – FiddleMeRagged
      Jan 27 '16 at 13:12











    • not works dude.

      – Sumit
      Dec 2 '16 at 12:23











    • @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

      – Jayprakash Dubey
      Apr 25 '17 at 12:34



















    -1














    For SWIFT 4:



    func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    completionHandler(
    .useCredential,
    URLCredential(trust: challenge.protectionSpace.serverTrust!)
    )
    }





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33128240%2fconnect-to-a-server-with-invalid-certificate-using-nsurlsession-swift2-xcode7-i%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      10














      Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.



      You'll most likely need the delegate method of the form,



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


      Adding this to my own comms class that uses NSURLSession fixed the issue.






      share|improve this answer


























      • It really works for me.

        – DawnSong
        Nov 12 '16 at 8:19






      • 1





        i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

        – Sumit
        Dec 2 '16 at 12:22
















      10














      Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.



      You'll most likely need the delegate method of the form,



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


      Adding this to my own comms class that uses NSURLSession fixed the issue.






      share|improve this answer


























      • It really works for me.

        – DawnSong
        Nov 12 '16 at 8:19






      • 1





        i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

        – Sumit
        Dec 2 '16 at 12:22














      10












      10








      10







      Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.



      You'll most likely need the delegate method of the form,



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


      Adding this to my own comms class that uses NSURLSession fixed the issue.






      share|improve this answer















      Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.



      You'll most likely need the delegate method of the form,



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


      Adding this to my own comms class that uses NSURLSession fixed the issue.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 28 '16 at 0:12









      alexeyB

      38110




      38110










      answered Jan 27 '16 at 13:15









      FiddleMeRaggedFiddleMeRagged

      2,1702026




      2,1702026













      • It really works for me.

        – DawnSong
        Nov 12 '16 at 8:19






      • 1





        i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

        – Sumit
        Dec 2 '16 at 12:22



















      • It really works for me.

        – DawnSong
        Nov 12 '16 at 8:19






      • 1





        i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

        – Sumit
        Dec 2 '16 at 12:22

















      It really works for me.

      – DawnSong
      Nov 12 '16 at 8:19





      It really works for me.

      – DawnSong
      Nov 12 '16 at 8:19




      1




      1





      i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

      – Sumit
      Dec 2 '16 at 12:22





      i added delegate but this method never called in swift 3, any other solutions without using alamofire or any other lib?

      – Sumit
      Dec 2 '16 at 12:22













      4














      When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:



      let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)


      Then, implement the following delegate method, it should work.



      func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
      let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
      completionHandler(.useCredential, urlCredential)
      }


      However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.






      share|improve this answer




























        4














        When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:



        let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)


        Then, implement the following delegate method, it should work.



        func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
        completionHandler(.useCredential, urlCredential)
        }


        However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.






        share|improve this answer


























          4












          4








          4







          When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:



          let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)


          Then, implement the following delegate method, it should work.



          func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
          let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
          completionHandler(.useCredential, urlCredential)
          }


          However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.






          share|improve this answer













          When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:



          let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)


          Then, implement the following delegate method, it should work.



          func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
          let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
          completionHandler(.useCredential, urlCredential)
          }


          However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jun 30 '17 at 19:55









          Debaditya SarkarDebaditya Sarkar

          514




          514























              0














              open your info.plist as a source code
              Add following:



                  <key>NSAppTransportSecurity</key>
              <dict>
              <key>NSAllowsArbitraryLoads</key>
              <true/>
              </dict>


              This should help.






              share|improve this answer



















              • 1





                I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

                – FiddleMeRagged
                Jan 27 '16 at 13:12











              • not works dude.

                – Sumit
                Dec 2 '16 at 12:23











              • @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

                – Jayprakash Dubey
                Apr 25 '17 at 12:34
















              0














              open your info.plist as a source code
              Add following:



                  <key>NSAppTransportSecurity</key>
              <dict>
              <key>NSAllowsArbitraryLoads</key>
              <true/>
              </dict>


              This should help.






              share|improve this answer



















              • 1





                I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

                – FiddleMeRagged
                Jan 27 '16 at 13:12











              • not works dude.

                – Sumit
                Dec 2 '16 at 12:23











              • @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

                – Jayprakash Dubey
                Apr 25 '17 at 12:34














              0












              0








              0







              open your info.plist as a source code
              Add following:



                  <key>NSAppTransportSecurity</key>
              <dict>
              <key>NSAllowsArbitraryLoads</key>
              <true/>
              </dict>


              This should help.






              share|improve this answer













              open your info.plist as a source code
              Add following:



                  <key>NSAppTransportSecurity</key>
              <dict>
              <key>NSAllowsArbitraryLoads</key>
              <true/>
              </dict>


              This should help.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Oct 14 '15 at 19:39









              Marcelo Pontes MachadoMarcelo Pontes Machado

              97118




              97118








              • 1





                I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

                – FiddleMeRagged
                Jan 27 '16 at 13:12











              • not works dude.

                – Sumit
                Dec 2 '16 at 12:23











              • @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

                – Jayprakash Dubey
                Apr 25 '17 at 12:34














              • 1





                I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

                – FiddleMeRagged
                Jan 27 '16 at 13:12











              • not works dude.

                – Sumit
                Dec 2 '16 at 12:23











              • @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

                – Jayprakash Dubey
                Apr 25 '17 at 12:34








              1




              1





              I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

              – FiddleMeRagged
              Jan 27 '16 at 13:12





              I don't see how this helps, as you're really just bypassing the IP addresses that the app talks to and not anything to do with server certificates?

              – FiddleMeRagged
              Jan 27 '16 at 13:12













              not works dude.

              – Sumit
              Dec 2 '16 at 12:23





              not works dude.

              – Sumit
              Dec 2 '16 at 12:23













              @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

              – Jayprakash Dubey
              Apr 25 '17 at 12:34





              @Marcelo : NSAllowsArbitaryLoads key when set to true will allows access to all unsecured URLs. So what is the point of having CER file for security?

              – Jayprakash Dubey
              Apr 25 '17 at 12:34











              -1














              For SWIFT 4:



              func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
              completionHandler(
              .useCredential,
              URLCredential(trust: challenge.protectionSpace.serverTrust!)
              )
              }





              share|improve this answer




























                -1














                For SWIFT 4:



                func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
                completionHandler(
                .useCredential,
                URLCredential(trust: challenge.protectionSpace.serverTrust!)
                )
                }





                share|improve this answer


























                  -1












                  -1








                  -1







                  For SWIFT 4:



                  func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
                  completionHandler(
                  .useCredential,
                  URLCredential(trust: challenge.protectionSpace.serverTrust!)
                  )
                  }





                  share|improve this answer













                  For SWIFT 4:



                  func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
                  completionHandler(
                  .useCredential,
                  URLCredential(trust: challenge.protectionSpace.serverTrust!)
                  )
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 1 at 10:17









                  kiran kumarkiran kumar

                  11914




                  11914






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33128240%2fconnect-to-a-server-with-invalid-certificate-using-nsurlsession-swift2-xcode7-i%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                      Npm cannot find a required file even through it is in the searched directory