2
votes

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.

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=Rome but I cannot find a way to add the 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?

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

How to keep the comma?

Thank you!

7
Here Coma(,) is encoded with %2C - Nirav D
Exactly... but here I'd need an url like: api.openweathermap.org/data/2.5/…. As before, this url works on the browser. - DungeonDev

7 Answers

5
votes

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

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 )

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)
            }
    }
2
votes
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)
                }
        }
}
1
votes

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:

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.

0
votes

Swift 5+ Use AF.request

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

**// Fist in third party liabrary, install pod 'Alamofire' Using Alamofire get json data

-1
votes

import UIKit import Alamofire class 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
}
}
}
}