如何在iOS中按多部分/表单数据发送字典?

时间:2020-09-15 05:21:16

标签: ios swift alamofire multipartform-data

我有以下复杂的词典:

    {
      "platform" : "ios",
      "data" : {
        "films" : [0],
        "about" : "",
        "is_voluntary" : true,
        "items" : [{
          "idx" : 0,
          "dates" : [
            "2020-09-23"
          ],
        "timelines" : [
          "11:00"
        ]
      }
    ],
    "language" : "en"
  },
  "app_version" : "2.1.0"
}

我的服务器端要求我使用multipart/form-data发送上述数据。我几乎不了解这种格式,但是这是我使用Alamofire的尝试:

 var initParams: [String: Any] = ....
 for (key, param) in initParams {
        if let array = param as? [String] {
            for item in array {
                if let data = item.data(using: .utf8) {
                    multipartData.append(data, withName: key)
                }
            }
        } else {
            if let data = "\(param)".data(using: .utf8) {
                multipartData.append(data, withName: key)
            }
        }
    }

multipartDataAlamofire.upload()函数中Alamofire的对象。但是,无论如何,以上都不起作用。我的服务器端告知我的方案中没有data。我哪里错了?如何正确转换任何对象以为form-data做准备?注意:JSONSerialization.data函数也不起作用。

1 个答案:

答案 0 :(得分:1)

这类似于下面的代码示例,我没有看到完整的字典,因此您可以看到示例并进行操作,

{
   "data": {
      "is_voluntary": true
   }
   "app_version": "1.2.3"
}

交换代码:

static func YourMethodName(app_version: String, , completion:@escaping (Bool)->Void) {
  var headers: HTTPHeaders!
  headers = [
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Your token",
        "Accept": "application/json"
             ]
  let url = "Your URL"
                
   AF.upload(multipartFormData: { (multiPart) in
        
   multiPart.append(Data("\(app_version)".utf8), withName: "app_version")
   multiPart.append(Data("\(true)".utf8), withName: "data[is_voluntary]")
        
  }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers).responseDecodable { (response:`enter code here` DataResponse<UserResponse>) in
   switch response.result {
          case .success(let userResponse):
                 // success data
          case .failure(_):
                 // failure data
          }
                    
   completion(response.response?.statusCode == 200)
  }
}