Swift - 是否可以解码 HTTP 响应 headers,以限制请求?
Swift - Is it possible to decode the HTTP response headers, for request limiting?
我正在使用 JSON 解码器和 URL session 从 API 解码 JSON。效果很好
URLSession.shared.dataTask(with: request) { (data, theResponse, error)
在“theResponse”(我没有解码)中,最后一个键是“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
);
} }
由于以上不是 JSON,是否可以将这些值解码为一种类型,然后我可以将其用于速率限制目的?
例如,当“X-RateLimit-requests-Remaining”达到 10
时限制我的应用内的请求
谢谢
这些已经为您解码成 [AnyHashable: Any]
字典。要获取这个特定的,您需要按照以下几行进行检查:
if let remaining = theResponse.allHeaderFields["X-RateLimit-requests-Remaining"]
as? Int { ... }
我正在使用 JSON 解码器和 URL session 从 API 解码 JSON。效果很好
URLSession.shared.dataTask(with: request) { (data, theResponse, error)
在“theResponse”(我没有解码)中,最后一个键是“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
);
} }
由于以上不是 JSON,是否可以将这些值解码为一种类型,然后我可以将其用于速率限制目的?
例如,当“X-RateLimit-requests-Remaining”达到 10
时限制我的应用内的请求谢谢
这些已经为您解码成 [AnyHashable: Any]
字典。要获取这个特定的,您需要按照以下几行进行检查:
if let remaining = theResponse.allHeaderFields["X-RateLimit-requests-Remaining"]
as? Int { ... }