Get header data from a request response in swift

前端 未结 1 1102
独厮守ぢ
独厮守ぢ 2021-02-13 22:13

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;
        \"Cont         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-13 22:40

    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
         }
    }
    

    0 讨论(0)
提交回复
热议问题