如何在 Swift 中使用 URLSession 时将数据传递到 header?
How to pass data into header while using URLSession in Swift?
我是 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") 我正在传递 API 密钥但奇怪的是我总是收到这样的回复
{
"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"
}
header 中的相同请求在 Postman 中完美运行,如下所示
我做错了什么?任何帮助将不胜感激
修改代码(仍然报同样的错误):
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()
}
好的方法,你用这个解决方案回答
我是 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") 我正在传递 API 密钥但奇怪的是我总是收到这样的回复
{
"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"
}
header 中的相同请求在 Postman 中完美运行,如下所示
我做错了什么?任何帮助将不胜感激
修改代码(仍然报同样的错误):
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()
}
好的方法,你用这个解决方案回答