簡體   English   中英

Alamofire 多部分請求

[英]Alamofire Multipart request

我是快速編程的新手。 我正在嘗試通過 alamofire 進行多部分請求。問題是我的參數中的一個值是對象數組。 我的問題是如何將對象數組附加到 Multipart 請求。 這是我的參數。

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

這是我的要求

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


        }

    },

    ...
)

將簽名者附加到多部分請求時應用程序崩潰。 這是我在參數中使用的對象。

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

請幫忙。 提前致謝,我浪費了兩天時間嘗試不同的事情。

多部分與 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)")
            }
        }

使用almofire多部分請求

數據發送到多部分

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

請求

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

不要忘記 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