所以我用莫亚创建了一个API请求来openweatherAPI,现在Postman上的返回似乎没问题,但是X-code上的API调用返回401:API密钥无效
我试过很多方法来找出问题所在,但似乎找不到答案。
import Foundation
import Moya
import UIKit
enum WeatherAPI {
case showCurrentWeather(cityName: String)
case showForcasedWeather(cityName: String)
}
extension WeatherAPI: TargetType {
var task: Task {
switch self {
case .showCurrentWeather(cityName: let cityName):
let params = ["q":cityName , "APPID": Constants.WEATHER_API_KEY]
return .requestParameters(parameters: params, encoding: JSONEncoding.default)
case .showForcasedWeather(cityName: let cityName):
let params = ["q":cityName , "APPID": Constants.WEATHER_API_KEY]
return .requestParameters(parameters: params, encoding: JSONEncoding.default)
}
}
var baseURL: URL {
return URL(string: "https://api.openweathermap.org/data/2.5")!
}
var path: String {
switch self {
case .showCurrentWeather:
return "/weather"
case .showForcasedWeather:
return "/forecast"
}
}
var method: Moya.Method {
switch self {
case .showCurrentWeather:
return .get
case .showForcasedWeather:
return .get
}}
var sampleData: Data {
return Data()
}
var headers: [String : String]? {
switch self {
case .showCurrentWeather:
return ["Content-type":"application/json"]
case .showForcasedWeather:
return ["Content-type":"application/json"]
}
}
}
https://api.openweathermap.org/data/2.5/weather?q=london&APPID=dbd3b02d8958d62185d02e944cd5f522
在Postman和浏览器上运行良好。
X代码退货
“代码”:401,“消息”:“API密钥无效。有关详细信息,请访问http://openweathermap.org/faq#error401。"}
1条答案
按热度按时间of1yzvn41#
应在任务变量中将此 JSONEncoding.default 更改为 URLEncoding.default。