使用Alamofire进行网络通话。我的要求是,需要在GET请求中发送正文。尝试了以下代码
func getForms(formTypes: [Int], userInterestIds:[Int], completionHandler: @escaping (_ status: Bool, _ response : GetArticleApiResponse?, _ error: Error?) -> Void) {
let headers = [
"Authorization" : "dfkjl23ksldjk3kd3",
"Content-Type": "application/json"
]
var parameters: Parameters = [:]
parameters["post_types"] = formTypes
parameters["usr_intrst_ids"] = userInterestIds
Alamofire.request(finalUrl, method: .get, parameters: parameters, headers: headers).responseJSON { response in
switch response.result {
case .success:
completionHandler(true,responseData, nil)
case .failure(let error):
completionHandler(false,nil,error)
}
}
但是,没有得到预期的响应。如果我做错了。帮我,如何实现以下邮递员呼叫。
谢谢。
答案 0 :(得分:0)
我个人会使用符合Codable协议的Struct。
struct MyStruct: Codable {
var post_types: [Int]
var usr_intrst_ids: [Int]
}
func getForms(formTypes: [Int], userInterestIds:[Int], completionHandler: @escaping (_ status: Bool, _ response : GetArticleApiResponse?, _ error: Error?) -> Void) {
let myStruct = MyStruct(post_types: formTypes, usr_intrst_ids: userInterestIds)
do {
json = try JSONEncoder().encode(myStruct)
var request = URLRequest(url: finalUrl)
request.httpMethod = HTTPMethod.get.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.setValue("dfkjl23ksldjk3kd3", forHTTPHeaderField: "Authorization")
request.httpBody = json
Alamofire.request(request).responseJSON { response in
...
}
} catch { // unable to encode myStruct }