我想在 header 请求中获取 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
获取 header
正如苹果文档所说:
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 information 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.
因此,例如,要在响应 header 中获取 X-Dem-Auth,您可以通过这种方式访问它:
if let httpResponse = response as? NSHTTPURLResponse {
if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
// use X-Dem-Auth here
}
}
更新
根据 Evan R 的评论更新
if let httpResponse = response as? HTTPURLResponse {
if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
// use X-Dem-Auth here
}
}
关于swift - 快速从请求响应中获取 header 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641700/