简体   繁体   English

我如何在字典中使用字典作为参数进行http get请求

[英]How can i make an http get request with dictionary as parameter in swift

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. 这是API调用,我该如何将字典作为参数传递给作为获取请求的URL,不要在其中使用Alamofire。

The URL is - http://mapi.trycatchtech.com/v1/naamkaran/post_list_by_cat_and_gender_and_page?category_id=3&gender=1&page=1 网址为-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)

    }

}

} }

SWIFT 4 / Xcode 10 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()
}

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

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