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,473
  • 35
  • 181
  • 253
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,945
  • 8
  • 32
  • 42
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
  • 2,113
  • 3
  • 20
  • 28
  • 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
  • 322
  • 4
  • 20