如何使用Swift 4从数据中使用Alamofire多部分以参数形式发送数组

时间:2018-07-17 11:42:03

标签: ios arrays swift3 multipartform-data alamofireimage

我正在使用Alamofire将图像和文件上传到服务器。但是我在发送带有图像参数的数组时遇到问题。但是,当我以参数形式发送数组时,它将转换为JSON字符串中的数组。但是我想用参数而不是JSON字符串发送数组。我已经搜索了很多,但没有得到任何解决方案。这是下面的代码。

let params = ["id":"101","arrayParam":["1232","12344","14325"]]

    let url = www.khxjjhdfsj.com/hsdgs
            let headers: HTTPHeaders = [
                /* "Authorization": "your_access_token",  in case you need authorization header */
                "Content-type": "multipart/form-data"
            ]
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                for (key, value) in params
                {
                     multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
                }
                if let data = imageData
                {
                    multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "image/png")
                }
                if let data = pdfData
                {
                    multipartFormData.append(data, withName: "file", fileName: fileName, mimeType:"application/pdf")
                }
            }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
                switch result{
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        print("Succesfully uploaded")
                        if let err = response.error
                        {
                            onError?(err)

                            return
                        }



                    }
                case .failure(let error):
                    print("Error in upload: \(error.localizedDescription)")
                    onError?(error)
                   }
            }

3 个答案:

答案 0 :(得分:0)

您可以尝试一下吗,也许您会得到

var dict = Data()
    let params:[String:Any] = ["id":"101","arrayParam":["1232","12344","14325"]]

for (key, value) in params {
    if key == "arrayParam" {
    if let str:[String] = value as? [String]{
          // to convert [String] to data
          dict = Data(buffer: UnsafeBufferPointer(start: str, count: str.count))
         // to retrive [String] from data
        let arr2 = dict.withUnsafeBytes {
            Array(UnsafeBufferPointer<String>(start: $0, count: dict.count/MemoryLayout<String>.stride))
        }
        print(arr2)
    }
    }
    multipartFormData.append(dict, withName: key)
    }

答案 1 :(得分:0)

28000000000
16000000000
33000000000
28000000000
27000000000
22000000000
26000000000
22000000000
22000000000
22000000000
46000000000

答案 2 :(得分:0)

我没有看到任何可接受的答案,所以分享我的解决方案。经过测试,可以正常工作。

let arrayObj = value as !Array<Any>
for i in 0..< arrayObj.count {
    let value = arrayObj[i] as !String
    let keyObj = key + "[" + String(i) + "]"
    form.append(value.data(using: String.Encoding.utf8)!, withName: keyObj)
}