1

I am using NSURLSession to request http post to server. It works fine if everything is ok. But I can't get the response when the server throw an exception. In browser, I should be able to get the 505 error code. But I can't get it in swift. Below is the code I used. Is there anything wrong with it?

let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
            (data, response, error) in
             //this method is not called
            print("get response from register service \(data) \(error)")

        })

        task.resume()
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523

1 Answers1

0

use this:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
        (let data, response, let error) in
        guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
            // no response code
            return
        }
        completeHandler(data, response, error)
    })
    task.resume()
Wajih
  • 4,227
  • 2
  • 25
  • 40
  • I have tried but it is still not working. The problem is that when server throw an exception, the completionHandler is not called. – Joey Yi Zhao Mar 20 '16 at 06:29
  • Did you mean that `// no response code` does not reach at all ? – Wajih Mar 20 '16 at 06:33
  • No, whenever the backend server throw an exception, the swift code is not called until timed out. When I use browser to access the same url, I can get the 505 internal error immediately. – Joey Yi Zhao Mar 20 '16 at 07:45