Swift中POST请求参数无法传递变量的问题排查与解决
问题:POST请求参数用变量返回空值,硬编码则正常
调用按国家获取城市数据的API时,遇到一个奇怪的问题:直接在请求体里写"country": "Nigeria"这类硬编码值,请求完全正常;但改用全局变量selectedCountryString处理后传入,返回结果为空。
初始有问题的代码
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()
修改后可正常运行的代码
改用Alamofire实现后,变量能正常传递参数,请求返回预期结果:
func callCitiesByPopAPI(completion: @escaping (CitiesPopModel?, Error?) -> ()) { let url = "https://countriesnow.space/api/v0.1/countries/population/cities/filter" let parameters: [String: Any] = [ "limit": 20, "order": "dsc", "orderBy": "value", "country": selectedCountryString ] AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseDecodable(of: CitiesPopModel.self) { response in if let error = response.error { completion(nil, error) return } if let result = response.value { completion(result, nil) print("City pop model result is \(result)") return } } }
问题排查总结
初始代码的问题大概率出在这几点:
- 对国家名称做了
lowercased()处理,而该API要求国家名称严格匹配大小写(比如"Nigeria"和"nigeria"不被识别为同一个国家) JSONSerialization使用.fragmentsAllowed选项可能导致JSON格式异常,Alamofire的JSONEncoding.default会自动处理标准的JSON序列化- 字符串插值
"\(myCountry)"可能引入了额外不可见字符,Alamofire对参数的处理更严谨
内容的提问来源于stack exchange,提问作者THEKRYS
相关产品推荐
相关产品推荐

