POST Request — iOS

Janvi Arora
3 min readMay 17, 2023

--

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var txtUID: UITextField!
@IBOutlet weak var txtTitle: UITextField!
@IBOutlet weak var txtBody: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func btnPostClick(_ sender: UIButton) {
self.setupPostMethod()
}

}

// https://jsonplaceholder.typicode.com/posts/
extension ViewController{
func setupPostMethod(){
guard let uid = self.txtUID.text else { return }
guard let title = self.txtTitle.text else { return }
guard let body = self.txtBody.text else { return }

if let url = URL(string: "https://jsonplaceholder.typicode.com/posts/"){
var request = URLRequest(url: url)
request.httpMethod = "POST"

let parameters: [String : Any] = [
"userId": uid,
"title": title,
"body": body
]

request.httpBody = parameters.percentEscaped().data(using: .utf8)

URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {
if error == nil{
print(error?.localizedDescription ?? "Unknown Error")
}
return
}

if let response = response as? HTTPURLResponse{
guard (200 ... 299) ~= response.statusCode else {
print("Status code :- \(response.statusCode)")
print(response)
return
}
}

do{
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}catch let error{
print(error.localizedDescription)
}
}.resume()
}
}
}

extension Dictionary {
func percentEscaped() -> String {
return map { (key, value) in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
}
}

extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="

var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}

Steps involved:

  1. The setupPostMethod() is a function that handles the setup and execution of an HTTP POST request to the URL "https://jsonplaceholder.typicode.com/posts/".
  2. Inside the method, the text values from the txtUID, txtTitle, and txtBody text fields are retrieved and assigned to the respective variables uid, title, and body using optional binding.
  3. The URL is then created using the URL(string:) initializer with the specified string value.
  4. A mutable URLRequest is created with the URL and the HTTP method is set to "POST" using request.httpMethod.
  5. The parameters dictionary is defined with the desired key-value pairs to be sent in the request body.
  6. The percentEscaped() function is called on the parameters dictionary to obtain a percent-encoded string representation of the key-value pairs. This function iterates over the dictionary, escapes the key and value using addingPercentEncoding(withAllowedCharacters:), and concatenates them with "=" as the separator and "&" as the joiner.
  7. The resulting percent-encoded string is converted to Data using .data(using: .utf8) and assigned to the httpBody property of the request.
  8. A URLSession data task is initiated with the request using URLSession.shared.dataTask(with:completionHandler:). Inside the completion handler, the response data, response object, and error are captured.
  9. If there is no data, the error (if present) is printed, and the function returns. If there is data, an HTTPURLResponse object is checked for a successful status code (200–299 range).
  10. If the status code is within the successful range, JSON serialization is performed on the data using JSONSerialization.jsonObject(with:options:) and the resulting JSON is printed.
  11. If there is an error during JSON serialization, the error description is printed.

Steps to keep in mind:

  1. Convert string to URL
  2. Generate a URL Request from URL.
  3. Give httpMethod for request. By default, httpMethod is GET
  4. Give parameter type
  5. Give httpBody to request.
  6. Create URLSession dataTask.
  7. Check if data is present and error is nil.
  8. Downcast response as HTTPURLResponse and check response status code. It should be 201 for a POST request.
  9. Perform JSONSerialisation with data. Use do-catch block.
  10. Resume task

Percent-encoded string representation of the dictionary’s key-value pairs:

let parameters = [
"name": "John Doe",
"age": 30,
"city": "New York"
]

Using the percentEscaped() function on this dictionary, we can generate a percent-encoded string representation of its key-value pairs. The resulting string will be formatted as a query string with percent-encoded values. Here's the example:

let percentEncodedString = parameters.percentEscaped()
print(percentEncodedString)

Output:

name=John%20Doe&age=30&city=New%20York

In the above example, the dictionary contains three key-value pairs: “name” with the value “John Doe”, “age” with the value 30, and “city” with the value “New York”. The percentEscaped() function converts these key-value pairs into a percent-encoded string representation, where spaces are replaced with %20 and special characters are properly encoded.

The resulting string can be used as query parameters in URLs, forming a valid URL-encoded representation of the dictionary’s contents.

--

--

No responses yet