简体   繁体   English

如何使用 swift 4 从数据中使用 Alamofire multipart 在 params 中发送数组

[英]How to send array in params using Alamofire multipart from data using swift 4

I am using Alamofire for uploading an image and a file to the server.我正在使用Alamofire将图像和文件上传到服务器。 But I am having an issue to send an array in parameters with the image.但是我在发送带有图像的参数数组时遇到问题。 But when I send an array in params it converts the array in JSON string.但是当我在 params 中发送一个数组时,它会将数组转换为JSON字符串。 But I want to send an array in params, not in JSON string.但我想在 params 中发送一个数组,而不是在JSON字符串中。 I have searched a lot but did not get any solution.我已经搜索了很多,但没有得到任何解决方案。 Here is the code below.这是下面的代码。

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

Can you try this, may be you will get你能试试这个吗,也许你会得到

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)
    }
 let params = [
        "key":value,
        "key1": key2] as [String : Any]



    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 30000

    manager.request(url, method: .post, parameters: params)
        .responseJSON {


            response in

            switch response.result {
            case .success:
               stopActivityIndicator()
                print(response)
                if let result = response.result.value {
                    let JSON = result as! NSDictionary
                    print(JSON)
                    let ResponseSuccess = JSON.object(forKey: "response")!
                    self.displayAlert(Message: ResponseSuccess as! String, myView:self)


                }


            case .failure( _):

                if let result = response.result.value {
                    stopActivityIndicator()
                    let JSON = result as! NSDictionary
                    print(JSON)
                    let ResponseFail = JSON.object(forKey: "response")!
                    self.displayAlert(Message: ResponseFail as! String, myView:self)
                }
            }


    }

I don't saw any accepted answer so sharing my solution.我没有看到任何被接受的答案,所以分享我的解决方案。 It's tested and working.它已经过测试并且可以正常工作。

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

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

相关问题 如何使用Alamofire multipart在params中发送数组 - How to send array in params using Alamofire multipart 我想使用 alamofire swift 5 将图像上传到多部分表单数据 - I want to upload image to multipart form data using alamofire swift 5 如何在 swift 5 中使用 Alamofire multipartFormData 发送数据和图像 - How to send data along with an image using Alamofire multipartFormData in swift 5 如何使用 Alamofire 5.0.0-beta.3 (Swift 5) 上传图像(多部分) - how to upload image (Multipart) using Alamofire 5.0.0-beta.3 (Swift 5) 如何在iOS,Swift3,Alamofire 4中使用多部分表单数据将图像作为参数上传以及其他参数 - How to upload image as a parameter, with other parameters using multipart form data in ios, swift3, Alamofire 4 如何使用Alamofire和Mailgun使用Swift发送电子邮件? - How to send email using Alamofire and Mailgun with Swift? 如何在Alamofire中使用multipart在多个图像阵列中上传多个图像? - How to upload multiple images in multiple array of images using multipart in Alamofire? 如何使用Swift 4和Alamofire从API抓取数据 - How to grab data from an API using Swift 4 and Alamofire 如何使用Alamofire快速从API获取空数据? - How to get an empty data from API using Alamofire in swift? 如何使用Alamofire快速从API提取数千个数据? - How to pull thousands of data from API using Alamofire in swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM