如何使用Alamofire在多部分表单数据中追加数组?

时间:2018-07-10 08:16:07

标签: ios ruby-on-rails swift alamofire multipartform-data

我正在使用Alamofire上传包含多部分表单数据的图像,但是在传递数组作为参数时遇到了一些问题。 This is postman request

根据请求,我需要将所有数据传递给letter。 这是我的工作方式。

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

    let paramArr : [String : Any] = [
        "message" : txtvwMessage.text!,
        "status": "draft",
        "recipient_ids": jsonString
    ]

    let parameter  : [String : Any] = ["letter" : paramArr]

    let accesstoken = Utilities.retriveValueFromDefault(forKey: UDKey.kUserAuthentication_Token) as String
    let client = Utilities.retriveValueFromDefault(forKey: UDKey.kUserClient) as String
    let uid = Utilities.retriveValueFromDefault(forKey: UDKey.kUserUID) as String


    let headersInfo : HTTPHeaders = [ "Content-Type" : "multipart/form-data",
                                      "Accept" : "application/json",
                                      "access-token" : accesstoken,
                                      "client" : client,
                                      "uid" : uid
    ]


    fileUploadWithParameter(Constant.ServerAPI.kPostLetters, images: letterImage, header: headersInfo, parameters: parameter, success: { (response) in

        print(response)
    }) { (progress) in


    }

这是Alamofire请求方法。

func fileUploadWithParameter(_ url: String,images:NSMutableArray,header : [String : String], parameters: [String:Any], success:@escaping (NSDictionary)->(),progressHandler:@escaping(_ progress: Double)->Void) {

    Alamofire.upload(multipartFormData: { multipartFormData in
        for i in 0..<images.count {

            let rotatedImage = images[i] as! UIImage

            if let imgData = UIImageJPEGRepresentation(rotatedImage, 0.8) {
                multipartFormData.append(imgData, withName: "letter[photos]",fileName: "0\(i).jpg", mimeType: "image/jpg")
            }
        }
        for (key, value) in parameters {

            //multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key )
            let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
            multipartFormData.append(paramsData, withName: key)

        }

    }, to: url,
       method:.post,
       headers:header) { (result) in
        print("\n\n\nRequest URL :- \(url)\nParameters :- \(parameters)")
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in

                if response.error != nil {
                    print("Error :- \((response.error?.localizedDescription)!)\n\n\n")
                }
                if let jsonDict = response.result.value as? NSDictionary {
                    print("Response :- \(jsonDict)\n\n\n")

                } else {
                    print("Error :- \(Constant.ErrorMessage.kCommanError)\n\n\n")

                }
            }
        case .failure(let encodingError):
            print("Error :- \(encodingError.localizedDescription)\n\n\n")

        }

    }
}

邮递员工作得很好,所以有人可以在我做错事的地方帮我。

期望使用API​​,正确的json应该是

 {
   "letter":
          {
            "message": "Type your message here...!!!",
            "recipient_ids": [183, 184],
            "status": "draft"
          }
 }

API在红宝石中运行,它说我正在发送字符串。请帮助我找出问题所在。

3 个答案:

答案 0 :(得分:0)

您可以在下方附加类似的数组

用于图像附件

for Attachment in Attachments
{
    if let pic = Attachment{
       let randome = arc4random()
       let data = UIImageJPEGRepresentation(pic, 0.8)
       MultipartFormData.append(data!, withName: "letter[photos][]", fileName: "randome\(randome).jpg", mimeType: "image/jpg")
                }
}

对于参数

for (key,value) in params
 {
   MultipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "\(key)")
 }

答案 1 :(得分:0)

最后通过在请求中添加单独的附件来完成它。这是如何以多部分形式传递数据请求的数组。

Alamofire.upload(multipartFormData: { multipartFormData in
        for i in 0..<self.letterImage.count {

            let rotatedImage = self.letterImage[i] as! UIImage

            if let imgData = UIImageJPEGRepresentation(rotatedImage, 0.8) {
                multipartFormData.append(imgData, withName: "letter[photos][]",fileName: "0\(i).jpg", mimeType: "image/jpg")
            }

        }

        multipartFormData.append("\(message)".data(using: String.Encoding.utf8)!, withName: "letter[message]")
        multipartFormData.append("draft".data(using: String.Encoding.utf8)!, withName: "letter[status]")

        for (_,value) in self.arrSelectedRecipientsID.enumerated() {

            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "letter[recipient_ids][]")
        }

    }

答案 2 :(得分:0)

Jus只需要更改给定的代码行:

  for (key, value) in parameters {
            if key == "letter" {
                let arrData =  try! JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
                multipartFormData.append(arrData, withName: key as String)
            }
            else {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
        }

其余部分相同。

您的方法以更新的形式:     func fileUploadWithParameter(_ url:字符串,图像:NSMutableArray,header:[String:字符串],参数:[String:Any],成功:@转义(NSDictionary)->(),progressHandler:@escaping(_进度:Double) ->无效){

    Alamofire.upload(multipartFormData: { multipartFormData in
        for i in 0..<images.count {

            let rotatedImage = images[i] as! UIImage

            if let imgData = UIImageJPEGRepresentation(rotatedImage, 0.8) {
                multipartFormData.append(imgData, withName: "letter[photos]",fileName: "0\(i).jpg", mimeType: "image/jpg")
            }
        }
        for (key, value) in parameters {

            //multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key )
            let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
            multipartFormData.append(paramsData, withName: key)

        }

        for (key, value) in parameters {
            if key == "letter" {
                let arrData =  try! JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
                multipartFormData.append(arrData, withName: key as String)
            }
            else {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
        }

    }, to: url,
       method:.post,
       headers:header) { (result) in
        print("\n\n\nRequest URL :- \(url)\nParameters :- \(parameters)")
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in

                if response.error != nil {
                    print("Error :- \((response.error?.localizedDescription)!)\n\n\n")
                }
                if let jsonDict = response.result.value as? NSDictionary {
                    print("Response :- \(jsonDict)\n\n\n")

                } else {
                    //print("Error :- \(Constant.ErrorMessage.kCommanError)\n\n\n")
                    print("Errfdc")
                }
            }
        case .failure(let encodingError):
            print("Error :- \(encodingError.localizedDescription)\n\n\n")

        }

    }
}