title: Moving from NSURLConnection to NSURLSession for SOAP POST in Swift
body: <p>I am trying to move over from NSURLConnection over to NSURLSession for a SOAP post, but seem to have issues with the NSURLSessionDataDelegate.</p>
  
  <p>Here is the old code in NSURLConnection that works fine:</p>
  
  <pre><code>let soapMessage = "&lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns1='http://tempuri.org/'&gt;&lt;SOAP-ENV:Body&gt;&lt;ns1:get_Countries/&gt;&lt;/SOAP-ENV:Body&gt;&lt;/SOAP-ENV:Envelope&gt;"
      print("Soap Packet is \(soapMessage)")
  
      let urlString = "https://example.com/Service.svc"
      let url = NSURL(string: urlString)
      let theRequest = NSMutableURLRequest(URL: url!)
      let msgLength = String(soapMessage.characters.count)
  
      theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
      theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
      theRequest.addValue("http://tempuri.org/IService/get_Countries", forHTTPHeaderField: "SoapAction")
      theRequest.HTTPMethod = "POST"
      theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
      print("Request is \(theRequest.allHTTPHeaderFields!)")
  
      let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: false)
      connection?.start()
  </code></pre>
  
  <p>This code then uses NSURLConnectionDelegate, and works fine as follows:</p>
  
  <pre><code>func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
      MutableData.length = 0;
      let httpresponse = response as? NSHTTPURLResponse
      print("status \(httpresponse?.statusCode)")
      //print("headers \(httpresponse?.allHeaderFields)")
  }
  
  func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
      MutableData.appendData(data)
  }
  
  
  func connection(connection: NSURLConnection, didFailWithError error: NSError) {
      NSLog("Error with Soap call: %@", error)
  
  }
  
  func connectionDidFinishLoading(connection: NSURLConnection!) {
      let xmlParser = NSXMLParser(data: MutableData)
      xmlParser.delegate = self
      xmlParser.parse()
      xmlParser.shouldResolveExternalEntities = true
  }
  
  func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
      if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust &amp;&amp; challenge.protectionSpace.host == "example.com" {
          NSLog("yep")
          let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust!)
          challenge.sender!.useCredential(credential, forAuthenticationChallenge: challenge)
      } else {
          NSLog("nope")
          challenge.sender!.performDefaultHandlingForAuthenticationChallenge!(challenge)
      }
  }
  </code></pre>
  
  <p>So that code all works fine, and is just for reference so you can see what I have done in the past, and the fact that the API actually does work!  However, if I move over to using NSURLSession and NSURLSessionDataDelegate instead then I cannot get it working correctly.  </p>
  
  <p>So here is the new code:</p>
  
  <pre><code>let soapMessage = "&lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns1='http://tempuri.org/'&gt;&lt;SOAP-ENV:Body&gt;&lt;ns1:get_Countries/&gt;&lt;/SOAP-ENV:Body&gt;&lt;/SOAP-ENV:Envelope&gt;"
      print("Soap Packet is \(soapMessage)")
  
      let urlString = "https://example.com/Service.svc"
      let url = NSURL(string: urlString)
      let theRequest = NSMutableURLRequest(URL: url!)
      let msgLength = String(soapMessage.characters.count)
  
      theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
      theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
      theRequest.addValue("http://tempuri.org/IService/get_Countries", forHTTPHeaderField: "SoapAction")
      theRequest.HTTPMethod = "POST"
      theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
      print("Request is \(theRequest.allHTTPHeaderFields!)")
  
  let config = NSURLSessionConfiguration.defaultSessionConfiguration()
  let session = NSURLSession(configuration:config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
  let task = session.dataTaskWithRequest(theRequest)
  task.resume()
  </code></pre>
  
  <p>My delegates I am using are NSURLSessionDelegate, NSURLSessionDataDelegate:</p>
  
  <pre><code>func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -&gt; Void) {
  
      print("Am in NSURLSessionDelegate didReceiveChallenge")
  
      if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust &amp;&amp; challenge.protectionSpace.host == "example.com" {
          NSLog("yep authorised")
          let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust!)
          challenge.sender!.useCredential(credential, forAuthenticationChallenge: challenge)
      } else {
          NSLog("nope")
          challenge.sender!.performDefaultHandlingForAuthenticationChallenge!(challenge)
      }
  
  }
  func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
      print("Am in URLSessionDidFinishEventsForBackgroundURLSession")
      let xmlParser = NSXMLParser(data: MutableData)
      xmlParser.delegate = self
      xmlParser.parse()
      xmlParser.shouldResolveExternalEntities = true
  }
  func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
      print("error of \(error)")
  }
  
  func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -&gt; Void) {
      print("Am in didReceiveResponse")
      MutableData.length = 0
  }
  
  
  func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
      print("Am in didReceiveData")
      MutableData.appendData(data)
  }
  
  func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
      print("error of \(error)")
  }
  </code></pre>
  
  <p>So, when I run the code, I get output:</p>
  
  <p>"Am in NSURLSessionDelegate didReceiveChallenge"
  "yep authorised"</p>
  
  <p>So it's getting to didReceiveChallenge fine, and it appears to be authorising the HTTPS secure certificate fine, but then nothing further happens, it doesn't do anything else, I'd expect it to go into didReceiveResponse then didReceiveData, but nothing further happens at all.</p>
  
  <p>So I am stuck, I could of course continue and use NSURLConnection as it all works fine, but I'd like to understand the NSURLSession, and particulary where I am going wrong.  So if anyone can help that would be great.</p>
  
  <p>Thanks</p>