Swift - Is it possible to decode the HTTP response headers, for request limiting?

746 views Asked by At

I am decoding a JSON from an API using JSONDecoder and URL session. It works great

URLSession.shared.dataTask(with: request) { (data, theResponse, error) 

Within "theResponse" (which I am not decoding), the last key is "X-RateLimit-requests-Remaining":

<NSHTTPURLResponse: 0x6000033ec300> { URL: myUrl } { Status Code: 200, Headers {
    Connection =     (
        "keep-alive"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        1913
    );
    "Content-Type" =     (
        "application/json"
    );
    Date =     (
        "Mon, 28 Sep 2020 14:34:35 GMT"
    );
    Server =     (
        "RapidAPI-1.2.6"
    );
    "X-RapidAPI-Region" =     (
        "AWS - eu-central-1"
    );
    "X-RapidAPI-Version" =     (
        "1.2.6"
    );
    "X-RateLimit-requests-Limit" =     (
        100
    );
    "X-RateLimit-requests-Remaining" =     (
        68
    );
} }

Since the above is not JSON, is it possible to decode these values into a type, that I can then use for rate limiting purposes?

For example, limiting requests within my app when "X-RateLimit-requests-Remaining" reaches 10

Thanks

1

There are 1 answers

0
Rob Napier On BEST ANSWER

These are already decoded for you, into a [AnyHashable: Any] dictionary. To fetch this particular one, you'd check it with something along these lines:

if let remaining = theResponse.allHeaderFields["X-RateLimit-requests-Remaining"] 
                       as? Int { ... }