I have defined the parameters to pass to rapidAPI using Alamofire
, but I've got an error.
I followed everything they said in the API documentation. If I put the full URL into a string it works fine, but when I pass as a parameter it doesn't
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
let CURRENT_BR_LEAGUE_URL = "https://api-football-v1.p.rapidapi.com/v2/leagues/country/"
override func viewDidLoad() {
super.viewDidLoad()
let params = ["country_name" : "england", "season" : "2018"]
getLeague(url: CURRENT_BR_LEAGUE_URL, parameters: params)
}
func getHeaders() -> [String : String] {
let headers = [
"X-RapidAPI-Host": "api-football-v1.p.rapidapi.com",
"X-RapidAPI-Key": "xxxxxxxxxxxxxxxxxxx"
]
return headers
}
func getLeague (url : String, parameters : [String : String]) {
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: getHeaders()).responseJSON {
response in
if response.result.isSuccess {
let leagueJSON : JSON = JSON(response.result.value!)
print(leagueJSON)
print()
}
else {
}
}
}
}
It throws a "wrong country" error. If I use full URL
let CURRENT_BR_LEAGUE_URL = "https://api-football-v1.p.rapidapi.com/v2/leagues/country/england/2018"
it works fine.
If I use "https://api-football-v1.p.rapidapi.com/v2/leagues/country/"
and set the parameters
let params = ["country_name" : "england", "season" : "2018"]
it does not work
As I looked now into RapidApi documentation for API-Football, you don't need the parameters. You just need to construct the URL from different parts and then make a GET request.
class ViewController: UIViewController {
let MAIN_URL = "https://api-football-v1.p.rapidapi.com/v2/leagues/country/"
override func viewDidLoad() {
super.viewDidLoad()
getLeague(for: "england", year: 2018)
}
func getHeaders() -> [String : String] {
let headers = [
"X-RapidAPI-Host": "api-football-v1.p.rapidapi.com",
"X-RapidAPI-Key": "xxxxxxxxxxxxxxxxxxx"
]
return headers
}
func getLeague (for country : String, year: Int) {
let url = MAIN_URL + country + "/\(year)/"
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: getHeaders()).responseJSON {
response in
if response.result.isSuccess {
let leagueJSON : JSON = JSON(response.result.value!)
print(leagueJSON)
print()
}
else {
}
}
}
}