Andro Developer
Andro Developer

Reputation: 1573

How to call a post web service with UrlSession.DataTaskPublisher?

I have a simple question that I can see only dataTaskPublisher in documentation with which I was able to call a get web service but how can I call a post web service which can return a publisher?

Upvotes: 4

Views: 3100

Answers (2)

Mac3n
Mac3n

Reputation: 4719

you can define a request and call it in your dataTaskPublisher like this :


var request =  URLRequest(url: URL(string: "url")!)
let session = URLSession.shared
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! JSONSerialization.dataWithJSONObject(parameters, options: [])
session.dataTaskPublisher(for: request)

Upvotes: 6

Asperi
Asperi

Reputation: 257603

Use constructor with URLRequest and prepare request with any HTTP method you need.

/// Returns a publisher that wraps a URL session data task for a given URL request.
///
/// The publisher publishes data when the task completes, or terminates if the task fails with an error.
/// - Parameter request: The URL request for which to create a data task.
/// - Returns: A publisher that wraps a data task for the URL request.
public func dataTaskPublisher(for request: URLRequest) -> URLSession.DataTaskPublisher

Upvotes: 3

Related Questions