gpt4 book ai didi

swift - 我如何在 swift 中以字典作为参数发出 http get 请求

转载 作者:行者123 更新时间:2023-11-30 11:05:16 24 4
gpt4 key购买 nike

这是 API 调用,我如何将字典作为参数传递给作为 get 请求的 URL,不想在其中使用 Alamofire。

网址是 - 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()


}

}

我在这里调用这个函数并传递字典值。

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

如果这是唯一的情况,一个简单的解决方案是:

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()
}

关于swift - 我如何在 swift 中以字典作为参数发出 http get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52804452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com