如何在Alamofire中将原始数据作为参数发布?

时间:2018-10-12 09:09:05

标签: ios iphone swift alamofire

如何在Alamofire中发布这种形式的参数?

[{"view_id":"108","Class_id":"VIII"}]

通常Alamofire接受[String:Any]个参数,当我在Alamofire请求中输入此参数时,它将引发错误:

"extra call method"

3 个答案:

答案 0 :(得分:2)

您说As normally Alamofire accept [String:Any] parameters,然后您通过[[String: Any]]

尝试在hhtpBody中传递数据。

let urlString            = "yourString"
guard let url = URL(string: urlString) else {return}
var request        = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
    request.httpBody   = try JSONSerialization.data(withJSONObject: your_parameter_aaray)
} catch let error {
    print("Error : \(error.localizedDescription)")
}
Alamofire.request(request).responseJSON{ (response) in
}

答案 1 :(得分:0)

您可以使用自定义编码在请求中发送参数。检查Alamofire docs on custom-encoding

SELECT P.Code,
       CASE PCD.ProductCharacteristicCode WHEN 10011786 THEN ISNULL(PCLD.ListValue,'') END AS [Sub Category] --This should achieve the same thing as the subquery with a subquery
       CASE PCD.ProductCharacteristicCode WHEN 10011787 THEN ISNULL(PCLD.ListValue,'') END AS [Brand]
FROM mstProduct P
     LEFT JOIN mstProductCharacteristicDetail PCD ON P.Code = PCD.ItemCode
     LEFT JOIN mstProductCharacteristicListDetail PCLD ON PCD.ProductCharacteristicCode = PCLD.HeaderCode
                                                      AND PCD.CharacteristicValue = SequenceNo;

使用方法:

struct JSONStringArrayEncoding: ParameterEncoding {
    private let jsonArray: [[String: String]]

    init(jsonArray: [[String: String]]) {
        self.jsonArray = jsonArray
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        let data = try JSONSerialization.data(withJSONObject: jsonArray, options: [])

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = data

        return urlRequest
    }
}

答案 2 :(得分:0)

试试这个方法来解决:

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: header).validate(statusCode: 200..<300) .responseJSON { response in
            

}