December 2018
Intermediate to advanced
414 pages
10h 19m
English
The counterpart to Decodable is Encodable; an object that conforms to both Encodable and Decodable is Codable. Now that you have seen how to download data from a server and parse it into a pure Swift object, you'll probably want to send data to the server from pure Swift objects:
func post<T, U>(url: URL, body: U, callback: @escaping (T?, Error?) -> Void) throws -> URLSessionTask where T: Decodable, U: Encodable { var request = URLRequest(url: url) request.httpBody = try JSONEncoder().encode(body) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request) { data, response, error in // Exact same code as in the get<T> callback, extracted handleResponse(data: data, response: response, ...
Read now
Unlock full access