POST Request — iOS
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:
- The
setupPostMethod()
is a function that handles the setup and execution of an HTTP POST request to the URL "https://jsonplaceholder.typicode.com/posts/". - Inside the method, the text values from the
txtUID
,txtTitle
, andtxtBody
text fields are retrieved and assigned to the respective variablesuid
,title
, andbody
using optional binding. - The URL is then created using the
URL(string:)
initializer with the specified string value. - A mutable
URLRequest
is created with the URL and the HTTP method is set to "POST" usingrequest.httpMethod
. - The
parameters
dictionary is defined with the desired key-value pairs to be sent in the request body. - The
percentEscaped()
function is called on theparameters
dictionary to obtain a percent-encoded string representation of the key-value pairs. This function iterates over the dictionary, escapes the key and value usingaddingPercentEncoding(withAllowedCharacters:)
, and concatenates them with "=" as the separator and "&" as the joiner. - The resulting percent-encoded string is converted to
Data
using.data(using: .utf8)
and assigned to thehttpBody
property of the request. - 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. - 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).
- 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. - If there is an error during JSON serialization, the error description is printed.
Steps to keep in mind:
- Convert string to URL
- Generate a URL Request from URL.
- Give httpMethod for request. By default, httpMethod is GET
- Give parameter type
- Give httpBody to request.
- Create URLSession dataTask.
- Check if data is present and error is nil.
- Downcast response as HTTPURLResponse and check response status code. It should be 201 for a POST request.
- Perform JSONSerialisation with data. Use do-catch block.
- 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.