简体   繁体   English

Alamofire 多部分请求

[英]Alamofire Multipart request

I am new to swift programming.我是快速编程的新手。 i am trying do Multipart request via alamofire .Issue is that one of value in my parameters is array of objects.我正在尝试通过 alamofire 进行多部分请求。问题是我的参数中的一个值是对象数组。 My Question is how to append array of object to Multipart request.我的问题是如何将对象数组附加到 Multipart 请求。 Here are my parameters.这是我的参数。

 let parameters = [
        "originguid":"63d6sd5",
        "signees":[Signess], //Here is issue "signees"is an array of objects
        "customer":"yes"
        ] as [String : Any]

here is my request这是我的要求

Alamofire.upload(
    .POST,
    URLString: myUrl,
    multipartFormData: { multipartFormData in

        if let img = self.imagePicked {
            multipartFormData.append(UIImageJPEGRepresentation(img, 0.2)!, withName: "fileset",fileName: "file.png", mimeType: "image/jpg")
        }
        if let file = self.filePicked{
            let fileData = try! Data(contentsOf: file)
            multipartFormData.append(fileData as Data, withName:"test.pdf", mimeType:"application/pdf")
        }

        for (key, value) in parameters {

            if key == "signees"{
                   multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }

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


        }

    },

    ...
)

Application crashes when appending signees to multipart request.将签名者附加到多部分请求时应用程序崩溃。 Here is my Object that i am using in parameters.这是我在参数中使用的对象。

class Signee: NSObject, NSCoding {
var name = ""
var email = ""
var phoneNo = ""
func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: "name")
    aCoder.encode(email, forKey: "email")
    aCoder.encode(phoneNo, forKey: "phoneNo")
}
init(name: String, email: String, phone: String) {
    self.name = name
    self.email = email

    self.phoneNo = phone

}
required convenience init(coder aDecoder: NSCoder) {
    let name = aDecoder.decodeObject(forKey: "name") as! String
    let email = aDecoder.decodeObject(forKey: "email") as! String
    let phoneNo = aDecoder.decodeObject(forKey: "phoneNo") as! String
    self.init(name: name, email: email, phone: phoneNo)
}}

Please help.请帮忙。 Thanks in advance, i have wasted two days trying different things.提前致谢,我浪费了两天时间尝试不同的事情。

Multipart with Alamofire多部分与 Alamofire

let headerDic: HTTPHeaders = [ "YOUR_HEADER_DIC" ]

let paramDic: Parameters = [ "YOUR_PARAMETER_DIC" ]

Alamofire.upload(multipartFormData: { (MultipartFormData) in

            MultipartFormData.append("YOUR_IMAGEDATA", withName: "YOUR_IMAGE_PARAMETER_NAME", fileName: "YOUR_IMAGENAME", mimeType: "image/jpeg")

            for (key, value) in paramDic {

                MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
            }

        }, to: "YOUR_WEBSERVICE_NAME", method: .post, headers: headerDic) { (result) in

            switch result {

            case .success(let upload, _, _):

                upload.responseJSON { response in

                    if let value = response.result.value {

                        let responseDic: NSDictionary = value as! NSDictionary

                             "YOUR_WEB_RESPONSE_SUCCESS_MESSEGE"

                        } else {

                            "YOUR_WEB_RESPONSE_ERROR_MESSEGE"
                        }
                    }
                }

            case .failure(let encodingError):

                var messege: String = String()

                if encodingError.localizedDescription.characters.count <= 0 {

                    messege = "Please check your Internet Conneciton!"

                } else {

                    messege = encodingError.localizedDescription
                }
                print("Error Messege:\(messege)")
            }
        }

Multipart Request using almofire使用almofire多部分请求

Data send into multipart数据发送到多部分

struct AGImageInfo {
    var fileName: String
    var type: String
    var data: Data
}

Request请求

let header: HTTPHeaders = [
    "Content-Type":"application/x-www-form-urlencoded"
]

let parameters: Parameters = [
    "someParam": "value",
    "Image": AGImageInfo(fileName: "nameOfImage.jpeg", type: "image/jpeg", data: #imageLiteral(resourceName: "TO").toData()!)
]

Alamofire.upload(multipartFormData: { (multipartFormData) in

    for (key, value) in parameters {
        if let imageData = value as? AGImageInfo {
            multipartFormData.append(imageData.data, withName: key, fileName: imageData.fileName, mimeType: imageData.type)
        }
        multipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
    }

}, to: "URL", method: .post, headers: header) { (result) in

    switch result {
    case .success(let upload, _, _):

        upload.responseJSON { response in
            switch response.result {
            case .success(let value):
                debugPrint(value)
                break

            case .failure(let error):
                debugPrint(error)
                break
            }
        }

    case .failure(let error):
        debugPrint(error)
        break
    }
}
struct File {
    var data: Data
    var name: String
    var mimeType: String
}
.upload(
         multipartFormData: { multipartFormData in
              for (key, value) in yourDictionnary {
                    if let file = value as? File {
                        multipartFormData.append(
                                file.data,
                                withName: key,
                                fileName: file.name,
                                mimeType: file.mimeType
                        )
                    } else {
                          multipartFormData.append(
                                (value as AnyObject).data(using: String.Encoding.utf8.rawValue)!,
                                withName: key
                            )
                        }
                    }
                },
                to: "Your URL"
            )

Don't forget the else case because you will go in the if and the second multipart.append you will get an error like this '-[Swift._SwiftDeferredNSArray dataUsingEncoding:]: unrecognized selector sent to instance 0x1c4421fa0'不要忘记 else 情况,因为你将进入 if 和第二个multipart.append你会得到这样的错误 '-[Swift._SwiftDeferredNSArray dataUsingEncoding:]: unrecognized selector sent to instance 0x1c4421fa0'

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

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