简体   繁体   English

如何附加字符串数组以形成数据

[英]how to append String Array to form data

I want to send file with other parameters.I was able to send that using alamofire upload.but the question is in my parameters i have String arrays.I dont know how to append them in to form data. 我想发送带有其他参数的文件。我能够使用alamofire upload。发送问题,但问题是我的参数中有String数组。我不知道如何将它们附加到表单数据中。

let parameters = ["comments":comments!,
                      "title":title!,
                      "publish_date":publish_date,
                      "expiry_date":expiry_date,
                      "visibility[staff]":"N",
                       "visibility[students][Forms]":["1","2"]

        ]
        ]
        as [String : Any]
    let headers = [

        "Content-type": "multipart/form-data"
    ]

    let URL_head = try! URLRequest(url: STAFF_SERVICE_URL + "staff/2/news?api_key=\(api_key)", method: .post, headers: headers)


    Alamofire.upload(multipartFormData: { (multipartFormData) in


        if let url = fileUrl{
            multipartFormData.append(url, withName: "file")
        }
        for (key, value) in parameters {
   multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)

        }
        print(multipartFormData)
    }, with:URL_head)
    { (result) in
        switch result {
        case .success(let upload, _, _):


            upload.responseJSON { response in
                NSLog("Upload  response \(response)")
                if let jsonValue = response.result.value {
                    _ = JSON(jsonValue)
                    completion(true ,"Suucess")


                }else{
                    completion(false ,"Error")
                }

            }

        case .failure(let encodingError):
            print("fail \(encodingError)")
            NSLog("Error \(result)")
            completion(false ,"No Internet")
        }

    }
}

i tried to encode array seperately like this.but not worked. 我试图像这样单独编码数组。但是没有用。

 let data = try! JSONSerialization.data(withJSONObject: array, 
 options:.prettyPrinted)
 let jsonString = String(data: data, encoding: .utf8)!

You can directly pass data object you don't need to convert back to string 您可以直接传递不需要转换回字符串的数据对象

for example 例如

 for (key, value) in parameters {
        if checkIfItIsArray {
            // Make sure you handle error here
            let data = try! JSONSerialization.data(withJSONObject: array,  options:nil)
           multipartFormData.append(data, withName: key as String)

        } else {
          multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
          }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM