-1

Hey so I have a website that has documentation to POST up information to it. The documentation telling how to post. Comes in a form like this.

Code From Documentation:

curl -X POST "https://api/management/user" \

-d "user_id=myuserid" \

-d "client=clientclientclient" \

-d "secret=secretsecret" 

I'm not sure how to write that out in a swift string.

Code:

let string = "https://api/management/user/user_id=myuserid/client=clientclientclient/secret=secretsecret"

Then I can do something like this.

Code:

  let url = NSURL(string: string)
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST"
    let session = URLSession.shared
    let tache = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
    print(data!)
    print(response!)

    }

    tache.resume()

Im NEW to this So what would be the proper way to write the post.

Hunter
  • 1,321
  • 4
  • 18
  • 34
  • By an POST request would the parameters send within the body! See this accepted answer for an example: https://stackoverflow.com/questions/6148900/append-data-to-a-post-nsurlrequest – matzino Nov 21 '17 at 21:38

1 Answers1

2

You will need to send the data as the HTTP body for the POST request.

if let theURL = URL.init(string:"https://api/management/user"{
   let request = URLRequest(url: theURL)
   request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
   request.httpMethod = "POST"
   let postString = "user_id=myuserid&client=clientclientclient&secret=secretsecret"
   if let encodedPostString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed), let body = encodedPostString.data(using:.utf8){
      request.httpBody = body
   }
   let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
      print(data!)
      print(response!)
    }
   task.resume()
}
Santhosh R
  • 1,518
  • 2
  • 10
  • 14