如何从HTTP获取状态代码获取swift?

时间:2015-01-08 07:56:53

标签: ios http swift

我已尝试使用以下代码在IOS Swift中实现HTTP Get。

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)")
        })

成功并显示以下回复:

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";
} }

如何从status code获取NSURLResponse

提前致谢。

1 个答案:

答案 0 :(得分:18)

NSURLResponse没有状态代码,但NSHTTPURLResponse有。所以投它:

let httpResponse = response as NSHTTPURLResponse
httpResponse.statusCode