简体   繁体   中英

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. My Question is how to append array of object to Multipart request. 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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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