One of the main points of this tutorial will be to explain and introduce the role of delegation in iOS development. Using delegates has many advantages. When we get a response from the server for the API request, the responsibility for handling or processing that response can be delegated to many different classes, whether that be the OxfordAPIClient class (implemented as a singleton, as will be seen in later tutorials), our unit testing classes (also to seen shortly), or the class that will utlimately be responsible for parsing the JSON data provided by the REST API. Furthermore, the delegation methods allow us to do some extra-preprocessing on the the server-provided response before we pass on that response to other classes that will deal with the respose for their own specific purposes (whether that be parsing the returned JSON data, executing XCTAssert statements, or logging output to the console). For our dictionary client, we define a protocol for a delegate below:
protocol OxfordDictionaryAPIDelegate{ typealias JSONResponse = DictionaryAPIClient.JSONResponse func didFailToConnectToEndpoint(withError error: Error) func didFailToGetJSONData(withHTTPResponse httpResponse: HTTPURLResponse) func didFailToSerializeJSONData(withHTTPResponse httpResponse: HTTPURLResponse) func didFinishReceivingHTTPResponse(withHTTPResponse httpResponse: HTTPURLResponse) func didFinishReceivingJSONData(withJSONResponse jsonResponse: JSONResponse, withHTTPResponse httpResponse: HTTPURLResponse) }
It will be noticed that the typealias for the JSONResponse, as defined in the DictionaryAPIClient is redeclared locally for convenience. This is a matter of preference on my part, as it has the benefit of increasing code readability. Also, it's very common in iOS nomenclature to prefix delegate functions with "will" (as in willConnectToEndpoint()) or "did"(as in didFailToGetJSONData(withHTTPResponse httpResponse: HTTPURLResponse)) depending on whether the callback function will be used to handle an event that has already happened or one that will take place at a future time.
To continue, please click here
If you feel confused or are having trouble following, you can go back to the previous page or back to the table of contents table of contents.