简体   繁体   中英

How to post raw data as a parameters in Alamofire?

How to post this form of parameters in Alamofire ?

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

As normally Alamofire accept [ String:Any] parameters and when I enter this parameter in Alamofire request then it raise an error :

"extra call method"

You said As normally Alamofire accept [String:Any] parameters and then you are passing [[String: Any]] .

Try to pass your data in 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
}

You can use custom encoding to send the params in request. Check the 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
    }
}

How to use:

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

}

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