微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从swift中的请求响应中获取头数据

我想在一个标题请求中获得X-Dem-Auth,swift在我的应用程序中存储它.

看到回复

headers {
    "Content-Length" = 95;
        "Content-Type" = "application/json; charset=utf-8";
        Date = "Fri,15 Apr 2016 08:01:58 GMT";
        Server = "Apache/2.4.18 (Unix)";
        "X-Dem-Auth" = null;
        "X-Powered-By" = Express;
如果响应是NSHTTPURLResponse的类型,则可以从response.allHeaderFields获取标头

正如苹果文档所说:

A dictionary containing all the HTTP header fields received as part of the server’s response. By examining this dictionary clients can see the “raw” header @R_695_4045@ion returned by the HTTP server.

The keys in this dictionary are the header field names,as received from the server. See RFC 2616 for a list of commonly used HTTP header fields.

因此,要获得响应标头中的X-Dem-Auth,您可以通过以下方式访问它:

if let httpResponse = response as? NSHTTPURLResponse {
     if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
        // use X-Dem-Auth here
     }
}

UPDATE

由于Evan R的评论而更新

if let httpResponse = response as? HTTPURLResponse {
     if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
        // use X-Dem-Auth here
     }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐