skip to Main Content

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 = .......?

2

Answers


  1. You can try

    request.httpBody = Data("yourString".utf8)
    
    Login or Signup to reply.
  2. You just need to convert the string to a Data, using data(using:):

    request.httpBody = "a simple string".data(using: .utf8)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search