xcode Alamofire 4 Swift 3 GET 请求与参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41364794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alamofire 4 Swift 3 GET request with parameters
提问by DungeonDev
I'm building a network stack using Alamofire 4 and Swift 3. Following the Alamofire guidelines I've created a router for the endpoints of the services. I'm currently using the free API of OpenWeatherMap but I'm finding problems in order to create a get request. That's the url needed: http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEY. Pasted on a browser, and using a real API Key it works and gives me back my nice json full of info about the weather in the given location. On my App I can insert the parameters as Dictionary but I cannot find a way to append the api key at the end of the url.
我正在使用 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 键的方法。
That's my enum router:
那是我的枚举路由器:
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
}
}
When I log my (urlRequest.url)! I have this: http://api.openweathermap.org/data/2.5/weather?q=Romebut I cannot find a way to add the apiKey. What am I doing wrong?
当我登录我的 (urlRequest.url) 时!我有这个:http: //api.openweathermap.org/data/2.5/weather?q=Rome 但我找不到添加 apiKey 的方法。我究竟做错了什么?
I've also made an ugly test adding this code after the print:
我还做了一个丑陋的测试,在打印后添加此代码:
var urlRequest2 = URLRequest(url: (urlRequest.url)!.appendingPathComponent(OWARouter.pathApiKey))
print("URL2: \(urlRequest2)")
And the log is URL2: http://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY?q=RomeHow come the api key is in the middle?
并且日志是 URL2:http://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY ?q=Rome api key 怎么在中间?
If you need this is the simple request code:
如果您需要这是简单的请求代码:
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)")
}
}
Another question... If I use as parameters ["q":"Rome, IT"], my output url is: http://api.openweathermap.org/data/2.5/weather?q=Rome%2CIT
另一个问题...如果我用作参数 ["q":"Rome, IT"],我的输出 url 是:http: //api.openweathermap.org/data/2.5/weather?q=Rome% 2CIT
How to keep the comma?
如何保留逗号?
Thank you!
谢谢!
回答by Kiran jadhav
Used below lines of code:
使用以下代码行:
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)")
}
}
}
}
回答by Manan Rami
Swift - 5 Alamofire 5.0 Updated Code(just Change AF.request Method according to your requirement you can add Parameters headers and intercepter as well )
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)
}
}
回答by Naimish Patel
func AlamofireGetCode()
{
var url:String!
url = "https://jsonplaceholder.typicode.com/comments"
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result{
case .success(let json):
print(json)
DispatchQueue.main.async {
print(json)
self.mainarray = json as? NSArray
print(self.mainarray as Any)
self.mytableviewreload.reloadData()
}
case .failure(let error):
print(error)
}
}
}
回答by DungeonDev
I've found a solution... the Api Key is simply a parameter to send to the request. So the code to change is not in the router but in the request function:
我找到了一个解决方案...... Api Key 只是一个发送到请求的参数。所以要改变的代码不在路由器中,而是在请求函数中:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome","APPID":"MY_API_KEY"])).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)")
}
}
EDIT: the comma issue do not gives me any problem now. Thank you.
编辑:逗号问题现在不给我任何问题。谢谢你。
回答by Abins Musthafa
import UIKit import Alamofire class APIWRAPPER: NSObject {
导入 UIKit 导入 Alamofire 类 APIWRAPPER: NSObject {
static let instance = APIWRAPPER()
func LoginAPI(Uname : String , Password : String) {
let requestString =
"http://************php/v1/sign-in"
let params = ["user_name": Uname,
"password": Password]
Alamofire.request(requestString,method: .get, parameters: params, encoding: JSONEncoding.prettyPrinted, headers: [:]).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil
{
print("response : \(response.result.value!)")
}
else
{
print("Error")
}
break
case .failure(_):
print("Failure : \(response.result.error!)")
break
}
}
}
}
回答by Astha Gupta
**// Fist in third party liabrary, install pod 'Alamofire' Using Alamofire get json data
**// 进入第三方库,安装pod 'Alamofire' Using Alamofire get json data