0

使用 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)
    }
}

但是,没有得到预期的回应。如果我做错了。帮帮我,如何实现下面的邮递员电话。

在此处输入图像描述

提前致谢。

4

1 回答 1

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 }
于 2019-06-29T02:26:52.873 回答