【发布时间】:2016-12-28 15:12:37
【问题描述】:
我正在使用 Alamofire 4 和 Swift 3 构建网络堆栈。按照 Alamofire 指南,我为服务的端点创建了一个路由器。我目前正在使用 OpenWeatherMap 的免费 API,但我发现问题是为了创建一个获取请求。 这就是所需的网址:http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEY。粘贴在浏览器上,并使用真正的 API 密钥,它可以工作,并返回我漂亮的 json,其中包含有关给定位置的天气信息。 在我的应用程序中,我可以将参数作为字典插入,但我找不到将 api 键附加到 url 末尾的方法。
这是我的枚举路由器:
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":"Rome, IT"] 作为参数,我的输出 url 是:http://api.openweathermap.org/data/2.5/weather?q=Rome%2CIT
如何保留逗号?
谢谢!
【问题讨论】:
-
这里
Coma(,)用%2C编码 -
完全正确...但在这里我需要一个类似的网址:api.openweathermap.org/data/2.5/…。和以前一样,这个 url 可以在浏览器上运行。
标签: ios swift xcode api alamofire