【问题标题】:How to get the status code from HTTP Get in swift?如何快速从 HTTP Get 获取状态码?
【发布时间】:2015-01-08 07:56:53
【问题描述】:

我已尝试使用以下代码在 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";
} }

如何从NSURLResponse 获取status code

提前致谢。

【问题讨论】:

标签: ios http swift


【解决方案1】:

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

let httpResponse = response as NSHTTPURLResponse
httpResponse.statusCode

【讨论】:

  • 是不是把response的类型改成NSHTTPURLResponse,得到statusCode?​​span>
  • 你不会通过强制转换来“改变”类型。正如您的打印显示类型已经是NSHTTPURLResponse,但您正在使用它的超类接口NSURLResponse。您需要通过转换访问状态码来更改界面。
猜你喜欢
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
相关资源
最近更新 更多