Alamofire 4とSwift 3を使用してネットワークスタックを構築しています。Alamofireのガイドラインに従って、サービスのエンドポイント用のルータを作成しました。私は現在、OpenWeatherMapの無料APIを使用していますが、取得リクエストを作成するために問題を見つけています。 それは必要なURL:http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEYです。ブラウザに貼り付けて、実際のAPIキーを使用して動作させ、与えられた場所の天気に関する情報が満載の素敵なjsonを返します。 私のアプリケーションでは、Dictionaryとしてパラメータを挿入できますが、URLの最後にapiキーを追加する方法が見つかりません。私の列挙型ルータですAlamofire 4 Swift 3パラメーター付きのGETリクエスト
:
enum OWARouter: URLRequestConvertible {
case byCityName(parameters: Parameters)
// MARK: Url
static let baseURLString = "http://api.openweathermap.org"
static let apiKey = "MY_APY_KEY"
static let pathApiKey = "&APPID=\(apiKey)"
var method: HTTPMethod {
switch self {
case .byCityName:
return .get
}
}
var path: String {
switch self {
case .byCityName:
return "/data/2.5/weather"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try OWARouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
switch self {
case .byCityName(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
print((urlRequest.url)!)
}
urlRequest.httpMethod = method.rawValue
return urlRequest
}
}
私は(urlRequest.url)にログインしたとき!私はこれを持っています:http://api.openweathermap.org/data/2.5/weather?q=Romeしかし、私はapiKeyを追加する方法を見つけることができません。 私は何が間違っていますか?
私も、印刷後にこのコードを追加醜いテストを行った:
var urlRequest2 = URLRequest(url: (urlRequest.url)!.appendingPathComponent(OWARouter.pathApiKey))
print("URL2: \(urlRequest2)")
、ログがURL2です:http://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY?q=Rome APIキーが真ん中にあるどのように来ますか?私はパラメータとして使用している場合
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome"])).responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
print(response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
もう一つの問題... :あなたは、これは単純な要求コードである必要がある場合
[ "Q": "ローマ、IT"]は、私の出力URLは次のとおりです。http://api.openweathermap.org/data/2.5/weather?q=Rome%2CIT
カンマを保持するにはどうすればよいですか?
ありがとうございました!
'昏睡(、)'ちょうど%2C –
でエンコードされた...しかし、ここで私のようなURLが必要と思います。http: //api.openweathermap.org/data/2.5/weather?q=Rome,It&APPID=MY_API_KEY。 以前と同じように、このURLはブラウザで動作します。 – DungeonDev