Dun*_*Dev 2 api xcode ios swift alamofire
我正在使用 Alamofire 4 和 Swift 3 构建网络堆栈。按照 Alamofire 指南,我为服务的端点创建了一个路由器。我目前正在使用 OpenWeatherMap 的免费 API,但为了创建获取请求,我发现了一些问题。这是所需的网址:http : //api.openweathermap.org/data/2.5/weather?q= Rome&APPID= MY_API_KEY。粘贴在浏览器上,并使用真正的 API 密钥,它可以工作并返回我的漂亮 json,其中包含有关给定位置的天气信息。在我的应用程序上,我可以将参数作为字典插入,但我找不到在 url 末尾附加 api 键的方法。
那是我的枚举路由器:
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
}
}
Run Code Online (Sandbox Code Playgroud)
当我登录我的 (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)")
Run Code Online (Sandbox Code Playgroud)
并且日志是 URL2:http ://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY ? q=Rome api key 怎么在中间?
如果您需要这是简单的请求代码:
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)")
}
}
Run Code Online (Sandbox Code Playgroud)
另一个问题...如果我用作参数 ["q":"Rome, IT"],我的输出 url 是:http : //api.openweathermap.org/data/2.5/weather? q=Rome% 2CIT
如何保留逗号?
谢谢!
Swift - 5 Alamofire 5.0 更新代码(只需根据您的要求更改 AF.request 方法,您也可以添加参数标头和拦截器)
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let json):
print(json)
DispatchQueue.main.async {
// handle your code
}
case .failure(let error):
print(error)
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下代码行:
func getRequestAPICall(parameters_name: String) {
let todosEndpoint: String = "your_server_url" + "parameterName=\(parameters_name)"
Alamofire.request(todosEndpoint, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
debugPrint(response)
if let data = response.result.value{
// Response type-1
if (data as? [[String : AnyObject]]) != nil{
print("data_1: \(data)")
}
// Response type-2
if (data as? [String : AnyObject]) != nil{
print("data_2: \(data)")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25824 次 |
| 最近记录: |