esantiago
esantiago

Reputation: 161

Swift 5: simple string URLRequest

I hope you can help me.

I am currently using native swift apis for URLSession and URLRequest network calls.

I have achieved the correct sending of json structures with the use of dictionaries.

let params: [String: Any] = ["user": "demo"]
var request = URLRequest(url: URL(string: "https://.....")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
    request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
  }catch _ {}

How would it be possible to send a simple string?

let params: "demo"
var request = URLRequest(url: URL(string: "https://.....")!)
request.httpMethod = "POST"
request.httpBody = .......?

Upvotes: 0

Views: 1293

Answers (2)

Sweeper
Sweeper

Reputation: 270995

You just need to convert the string to a Data, using data(using:):

request.httpBody = "a simple string".data(using: .utf8)

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

request.httpBody = Data("yourString".utf8)

Upvotes: 0

Related Questions