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.
URLRequest Objectvar urlRequest = URLRequest(url: URL(string: Endpoint.registerUser)!)
urlRequest.httpMethod = "post"
Explanation:
URLRequest Initialization: This creates an instance of URLRequest using the URL for the API endpoint. The URL(string: Endpoint.registerUser)! creates a URL object from the endpoint string defined in your Endpoint struct.httpMethod to "post" specifies that this request will be a POST request, as opposed to a GET or another type of HTTP method.UserRegistrationRequest Objectlet request = UserRegistrationRequest(Name: "ravi", Email: "[email protected]", Password: "1234")
Explanation:
UserRegistrationRequest with the necessary user data to be sent in the body of the POST request. Encodable ensures that this struct can be converted to JSON format.do {
let requestBody = try JSONEncoder().encode(request)
urlRequest.httpBody = requestBody
urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
} catch let error {
debugPrint(error.localizedDescription)
}
Explanation:
JSONEncoder().encode(request) converts the UserRegistrationRequest object into JSON data. This is necessary because the server expects the request body to be in JSON format.urlRequest.httpBody = requestBody sets this JSON data as the body of the POST request.urlRequest.addValue("application/json", forHTTPHeaderField: "content-type") specifies the content type of the request body as JSON. This informs the server that the request payload is in JSON format.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()