简体   繁体   English

Alamofire 4 Swift 3 GET 请求与参数

[英]Alamofire 4 Swift 3 GET request with parameters

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.我正在使用 Alamofire 4 和 Swift 3 构建网络堆栈。按照 Alamofire 指南,我为服务的端点创建了一个路由器。 I'm currently using the free API of OpenWeatherMap but I'm finding problems in order to create a get request.我目前正在使用 OpenWeatherMap 的免费 API,但为了创建获取请求,我发现了一些问题。 That's the url needed: http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEY .这是所需的网址: 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.粘贴在浏览器上,并使用真正的 API 密钥,它可以工作并返回我的漂亮 json,其中包含有关给定位置的天气信息。 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.在我的应用程序上,我可以将参数作为字典插入,但我找不到在 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)!当我登录我的 (urlRequest.url) 时! I have this: http://api.openweathermap.org/data/2.5/weather?q=Rome but I cannot find a way to add the apiKey.我有这个: http ://api.openweathermap.org/data/2.5/weather?q=Rome 但我找不到添加 apiKey 的方法。 What am I doing wrong?我究竟做错了什么?

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=Rome How 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!谢谢!

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)")
                    }
                }
            }
    }

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)
            }
    }
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)
                }
        }
}

I've found a solution... the Api Key is simply a parameter to send to the request.我找到了一个解决方案...... Api Key 只是一个发送到请求的参数。 So the code to change is not in the router but in the request function:所以要更改的代码不在路由器中,而是在请求函数中:

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.谢谢你。

Swift 5+ Use AF.request Swift 5+使用AF.request

 let todosEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
    let request = AF.request(todosEndpoint)
    request.responseJSON { (data) in
        print("Response", data)
    }

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
}
}
}
}

**// 进入第三方库,安装 pod 'Alamofire' Using Alamofire get json data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM