Get header data from a request response in swift

拥有回忆 提交于 2020-02-26 16:04:28

问题


I want to get X-Dem-Auth in a header request with swift to stock that in my app.

See the response :

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;

回答1:


If the response is type of NSHTTPURLResponse you can get header from response.allHeaderFields

As apple documentation says :

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.

So to get for example a X-Dem-Auth in response header you can access it in that way :

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

UPDATE

Updated due to comment from Evan R

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


来源:https://stackoverflow.com/questions/36641700/get-header-data-from-a-request-response-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!