alphanso
alphanso

Reputation: 409

RxAlamofire make post call with json body

I want to make post call using RxAlamofire not able to find any method to do so

tried using requestJSON method but there is no paramter to pass post json in

 RxAlamofire.requestJSON(.post, url)

how to make post call and pass json data to post call in RxAlamofire

Upvotes: 0

Views: 2317

Answers (4)

Songzhw
Songzhw

Reputation: 169

amodkanthe's solution works. But its return value is not friendly. So I changed it a litte bit

    var request = URLRequest(url: URL(string: "https://some_url")!)
    request.httpBody = jsonData  // jsonData is a Data type
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type") // this line is important
    RxAlamofire.requestJSON() //=> returns a Observable<(HttpURLResponse, Any)>, the `Any` type is actually a dictionary

p.s. the version I'm using is RxAlamofire(6.1.1)

Upvotes: 0

Versus
Versus

Reputation: 414

Using jsonEncoding

RxAlamofire.requestJSON(.post, url, encode: JsonEncoding.default)

It works for me~

Upvotes: -1

amodkanthe
amodkanthe

Reputation: 4530

Use following code

  var request = URLRequest(url: URL(string: "https://some_url")!)
    //Following code to pass post json 
    request.httpBody = json
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    RxAlamofire.request(request as URLRequestConvertible).responseJSON().asObservable()

Upvotes: 1

mkowal87
mkowal87

Reputation: 626

use this function with proper parameters ancoding

public func urlRequest(_ method: Alamofire.HTTPMethod,
                   _ url: URLConvertible,
                   parameters: [String: Any]? = nil,
                   encoding: ParameterEncoding = URLEncoding.default,
                   headers: [String: String]? = nil)

Upvotes: 0

Related Questions