0

Here is the API Call how can I pass a dictionary as the parameter to the URL which is a get request, Don't want to use Alamofire in this.

The URL is - http://mapi.trycatchtech.com/v1/naamkaran/post_list_by_cat_and_gender_and_page?category_id=3&gender=1&page=1

func getDisplayJsonData(url: String, parameters: [String: Any], completion: @escaping displayCompletionHandler) {

    guard let url = URL(string: url) else {return}



    URLSession.shared.dataTask(with: url) { (data, response, error) in

        if error != nil {
            debugPrint(error?.localizedDescription ?? "")
            completion(nil)
            return
        } else {

            guard let data = data else {return completion(nil)}
            let decoder = JSONDecoder()

            do{
                let displayJson = try decoder.decode(Display.self, from: data)
                completion(displayJson)
            } catch{
                debugPrint(error.localizedDescription)
                completion(nil)
                return
            }

        }

    } .resume()


}

}

Where I am calling this function here and passing the dictionary values.

extension DisplayVC {

func getData() {

    let params = ["category_id": categoryId, "gender": genderValue, "page": pageNumber] as [String : Any]

    DisplayService.instance.getDisplayJsonData(url: BASE_URL, parameters: params) { (receivedData) in

        print(receivedData)

    }

}

}

Ajinkya Sonar
  • 38
  • 1
  • 9

1 Answers1

2

SWIFT 4 / Xcode 10

If this the only case, a simple solution is:

func getDisplayJsonData(url: String, parameters: [String: Any], completion: @escaping displayCompletionHandler) {

    var urlBase = URLComponents(string: url)

    guard let catValue = parameters["category_id"] as? Int else {return}
    guard let genderValue = parameters["gender"] as? Int else {return}
    guard let pageValue = parameters["page"] as? Int else {return}

    urlBase?.queryItems = [URLQueryItem(name: "category_id", value: String(catValue)), URLQueryItem(name: "gender", value: String(genderValue)), URLQueryItem(name: "page", value: String(pageValue))]

    //print(urlBase?.url)

    guard let urlSafe = urlBase?.url else {return}

    URLSession.shared.dataTask(with: urlSafe) { (data, response, error) in

        //Your closure

        }.resume()
}
FRIDDAY
  • 3,781
  • 1
  • 29
  • 43
  • Assume you ave a fixed dictionary with known keys. if you don't know how many keys your dictionary has, you can loop through and get the keys and values. – FRIDDAY Oct 14 '18 at 18:18