13

I am following this answer for making HTTP calls in my swift project. How to make an HTTP request in Swift?

and following is the code I am using to make a synchronous call

let urlPath: String = "http://apiserver.com/api/login/?username=asdf&password=asdf"
            var url: NSURL = NSURL(string: urlPath)!
            var request1: NSURLRequest = NSURLRequest(URL: url)

            var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil

            var error: NSErrorPointer = nil
            var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
            var err: NSError

            println("response -- \(response)")
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

            println("Synchronous \(jsonResult)")

is here anyone who can help me to get HTTP Header Response or status code by using this code? please

Jabbar
  • 590
  • 1
  • 7
  • 21

3 Answers3

20

Try this:

 func getData(url: NSURL) {
    let config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session: NSURLSession = NSURLSession(configuration: config)

    let dataTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data: NSData!, urlResponse: NSURLResponse!, error: NSError!) -> Void in

        if let httpUrlResponse = urlResponse as? NSHTTPURLResponse
        {
            if error {
                println("Error Occurred: \(error.localizedDescription)")
            } else {
                println("\(httpUrlResponse.allHeaderFields)") // Error
            }
        }
        })

       dataTask.resume()
    }
iAnurag
  • 9,286
  • 3
  • 31
  • 48
  • I already tried this. getting a warning. That says "Cast from AutoreleasingUnsafeMutablePointer to unrelated type NSHTTPURLResponse always fails" – Jabbar Aug 21 '15 at 13:01
  • I got this Response Now: [Keep-Alive: timeout=5, max=100, Expires: Thu, 19 Nov 1981 08:52:00 GMT, Transfer-Encoding: Identity, Server: Apache/2.4.12 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4, Content-Type: text/html, Connection: Keep-Alive, Pragma: no-cache, Cache-Control: no-store, no-cache, must-revalidate, post-check=0, ........................................................ No Status code. – Jabbar Aug 21 '15 at 13:39
  • How to get the value by key ?. – Bhimbim Aug 14 '19 at 12:23
3

Per your code in the original question, have you tried this?

let urlPath: String = "http://apiserver.com/api/login/?username=asdf&password=asdf"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)

var response: NSURLResponse? = nil

var error: NSError? = nil
var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error:&error)!
var err: NSError

println("response -- \(response)")
if let response = response as? NSHTTPURLResponse {
    if response.statusCode == 200 {
        print("Success")
    }
}
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

println("Synchronous \(jsonResult)")
Jabbar
  • 590
  • 1
  • 7
  • 21
Matt Mathias
  • 932
  • 7
  • 7
  • I tried this but on success I got statusCode = 200 but when it fails it returns nil.... any suggestion.? – Jabbar Aug 24 '15 at 05:49
  • I updated the answer to make use of `error` in `sendSynchronousRequest(_:returningResponse:error:)`. Put a breakpoint after you send the request to see why it fails. For example, if the request fails because of a bad password, then `error` has information in it to identify that problem. – Matt Mathias Aug 24 '15 at 13:40
0

Extension to retrive header field

extension URLResponse {
    func headerField(forKey key: String) -> String? {
        (self as? HTTPURLResponse)?.allHeaderFields[key] as? String
    }
}

Usage

var urlResponse: URLResponse = ...
let headerField = urlResponse.headerField(forKey: "retry-after")
Ramis
  • 13,985
  • 7
  • 81
  • 100