douyong1905 2014-12-05 06:25
浏览 185

Swift:从Server Response获取HTTP代码

I'm using the following function in Swift to connect to a PHP Script on a server and then process my request:

func pushtoserveronclick() {
    var URL: NSURL = NSURL(string: "http://someurl.com/")!
    var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"
    var bodyData = "data=something&version=\(appVersion)"
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
        {
            (response, data, error) in                       
            println(response)                
    }
 }

When I run the app I get this returned as the response:

<NSHTTPURLResponse: 0x14e53170> { URL: http://someurl.com/ } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "text/html";
Date = "Fri, 05 Dec 2014 06:23:23 GMT";
"Keep-Alive" = "timeout=2, max=100";
Server = Apache;
"Transfer-Encoding" = Identity;

How would I get the status code that is being returned so I can perform a check on it and tell whether or not it's a connection issue?

  • 写回答

1条回答 默认 最新

  • dpt1712 2014-12-05 19:54
    关注

    NSURLConnection.sendAsynchronousRequest uses NSURLResponse in the type signature, but as long as you're connecting over HTTP, the instance is (usually) NSHTTPURLResponse, which has the statusCode.

    You can check and cast it this way:

    if let HTTPResponse = response as? NSHTTPURLResponse {
        let statusCode = HTTPResponse.statusCode
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)