我是 swift 新手,正处于学习阶段。
我基本上必须使用 URLSession 发出请求,但 API 不允许任何未经授权的请求
这是我的代码:
func getCoinPrice(for currency: String) {
let urlString = baseURL + currency
guard let url = URL(string: urlString) else {
return
}
var request = URLRequest(url: url)
request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
let dataAsString = String(data: data!, encoding: .utf8)
print(dataAsString ?? "NO VALUE")
}
task.resume()
}
我有行 request.setValue(apiKey, forHTTPHeaderField: "CoinAPI-Key") 我在其中传递 APIkey 但奇怪的是我总是得到这个响应
{
"error": "You didn\u0027t specify API key or it is incorrectly formatted. You should do it in query string parameter \u0060apikey\u0060 or in http header named \u0060X-CoinAPI-Key\u0060"
}
我做错了什么?任何帮助将不胜感激
修改代码(仍然出现相同的错误):
func getCoinPrice(for currency: String) {
let urlString = baseURL + currency
var urlComponent = URLComponents(string: urlString)
urlComponent?.queryItems = [URLQueryItem(name: apiKey, value: "x-api-key")]
let request = URLRequest(url: urlComponent!.url!)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
let dataAsString = String(data: data!, encoding: .utf8)
print(dataAsString ?? "NO VALUE")
}
task.resume()
}
这个问题可能早已得到解答,但您从未在代码中为 apiKey 变量设置值。
urlComponent?.queryItems = [URLQueryItem(名称: apiKey, 值: "x-api-key")]
此处的行使用 apiKey 变量,但在它之前(或至少在共享的代码中)没有一行表示以下内容:
let apiKey = "这里是你的 api 密钥"
您可以将代码行替换为:
urlComponent?.queryItems = [URLQueryItem(名称:“此处为您的 API 密钥”,值:“x-api-key”)]
这也可能会解决您的问题(如果尚未解决)。