2

How to post a json string using Alamofire. Alamofire request takes only Dictionary type as parameter: [String : Any]. But I want to pass a json string as a parameter, not Dictionary.

Alamofire.request(url, method: .post, 
         parameters: [String : Any], // <-- takes dictionary !!
         encoding: JSONEncoding.default, headers: [:])
Eric Aya
  • 69,000
  • 34
  • 174
  • 243
kavinraj M
  • 149
  • 2
  • 5

3 Answers3

1

The easiest way is to convert your json data to native dictionary and use it as intended:

func jsonToDictionary(from text: String) -> [String: Any]? {
    guard let data = text.data(using: .utf8) else { return nil }
    let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: Any]
}

Usage:

var params = jsonToDictionary(from: json) ?? [String : Any]()
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:])
Hexfire
  • 5,644
  • 8
  • 30
  • 41
0

You are using encoding: JSONEncoding.default and your parameter data in the form of [String : Any] while you passing the data Alamofire encode your [String : Any] to json becuse you already mentioned your encoding method will be JSONEncoding.default server will receive encoded JSON

Ganesh Manickam
  • 1,962
  • 3
  • 18
  • 27
  • this is not what OP sought after; he wants to pass a string instead of a dict. E.g.: "This is a string", *BUT* ["this is" : "dictionary"] – Antek Apr 03 '18 at 13:03
0

duplicate:POST request with a simple string in body with Alamofire

extension String: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }

}

Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
Karim
  • 194
  • 3
  • 19