Home > Net >  Variable Not Passing In POST parameter in Swift
Variable Not Passing In POST parameter in Swift

Time:10-10

I'm trying to get the cities by country using the POSTMAN Api. When I don't bring any variables into the parameter, the request works as expected. Though, when I try to use a global variable as a parameter, it throws an error. It works perfectly fine if it was coded as such: "country": "Nigeria" (everything else the same)

Code below:

let myCountry = selectedCountryString.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
    guard let url = URL(string: "https://countriesnow.space/api/v0.1/countries/population/cities/filter") else {
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")   
    let body: [String: Any] = [
    
        "limit": 10,
        "order": "dsc",
        "orderBy": "value",
        "country": "\(myCountry)"

    ]
    
    request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
    let task = URLSession.shared.dataTask(with: request) {data, _, error in
        guard let data = data, error == nil else {
            return
        }
        do{                
            let response = try JSONDecoder().decode(CitiesPopModel.self, from: data)
            onCompletion(response)
        } 
        catch {
            print("Error country -> \(myCountry)")              
        }
    }       
    task.resume()       
}

CodePudding user response:

Replace value forHttpHeaderField for this:

request.setValue("application/json", forHTTPHeaderField: "Accept")

CodePudding user response:

Not worry about it you have to pass selectedCountryString value as like it then all goes perfectly

let selectedCountryString = "INDIA"

  • Related