How to get the status code from HTTP Get in swift?

11,335

NSURLResponse do not have status code, but NSHTTPURLResponse does. So cast it:

let httpResponse = response as NSHTTPURLResponse
httpResponse.statusCode
Share:
11,335
Martin
Author by

Martin

Updated on July 18, 2022

Comments

  • Martin
    Martin almost 2 years

    I have try the following code to implement HTTP Get in IOS Swift.

    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: {(response: NSURLResponse!, data: NSData!,error: NSError!) -> Void in
    
                var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                println("response = \(response)")
            })
    

    It success and show the following response:

    response = <NSHTTPURLResponse: 0x155xxxxx> { URL: http://xxx.xx.xxx.xxx:38080/getid/user-wiced1 } 
    { status code: 200, headers {
        "Content-Length" = 111;
        "Content-Type" = "application/json; charset=UTF-8";
        Date = "Thu, 08 Jan 2015 07:31:21 GMT";
        Server = "spray-can/1.3.2-20140909";
    } }
    

    How to get the status code from NSURLResponse ?

    Thanks in advance.

  • Martin
    Martin over 9 years
    Is it mean change the type of response to the NSHTTPURLResponse , and get the statusCode?
  • Kirsteins
    Kirsteins over 9 years
    You do not "change" the type by casting. As your print show the type is already NSHTTPURLResponse, but your are using it superclass interface NSURLResponse. You need to change interface by casting to access status code.