The Encodable protocol in Swift is used to define how instances of a type can be converted into a format that can be stored or transmitted, such as JSON or XML. By conforming to Encodable, a type provides a way to encode its data into a serialized format. This is particularly useful when sending data from a Swift application to a server, or when saving data to a file. The Encodable protocol allows for customization of the encoding process through the use of encoding containers, which map properties of a type to keys in the serialized output. Swift's Codable protocol, which combines Encodable and Decodable, simplifies this process, enabling seamless conversion between complex data types and their serialized representations.

1. Creating the URLRequest Object

var urlRequest = URLRequest(url: URL(string: Endpoint.registerUser)!)
urlRequest.httpMethod = "post"

Explanation:

2. Creating the UserRegistrationRequest Object

let request = UserRegistrationRequest(Name: "ravi", Email: "[email protected]", Password: "1234")

Explanation:

3. Encoding the Request Object to JSON

do {
    let requestBody = try JSONEncoder().encode(request)
    urlRequest.httpBody = requestBody
    urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
} catch let error {
    debugPrint(error.localizedDescription)
}

Explanation:

4. Making the Network Request

URLSession.shared.dataTask(with: urlRequest) { (data, httpUrlResponse, error) in
    if(data != nil && data?.count != 0) {
        do {
            // Uncomment this code to view the server response in console
            // let str = String(decoding: data!, as: UTF8.self)
            // debugPrint(str)
            let response = try JSONDecoder().decode(UserRegistrationResponse.self, from: data!)
            print("This is the data sent")
            debugPrint(response.data.name, response.data.email, response.data.id)
        }
        catch let decodingError {
            debugPrint(decodingError)
        }
    }
}.resume()