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

问题描述 投票:1回答:2

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

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

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

"extra call method"
ios iphone swift alamofire
2个回答
3
投票

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

尝试在http Body中传递您的数据。

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
}

0
投票

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

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

如何使用:

Alamofire.request("https://myserver.com/api/path", method: .post, encoding: JSONStringArrayEncoding).responseJSON { response in

}
© www.soinside.com 2019 - 2024. All rights reserved.