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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀