Perks Game Mechanic - Service Call

The game is coming along and I have settled on what I hope is an interesting mechanic for character perks. I recently stumbled upon Wordnik a website which purports to be ‘all the words’. They have an API which will give you words and their definitions in various configurations. As I am a product of U.S. public education system test taking is near and dear to my heart so my first thought was to attach this to some sort of dialogue view for quizzes. The player would be presented a word, asked to select the correct definition or usage, and then earn perks for correct answers. All of that might work, but the first step is grabbing data from the API. It’s a pickle!

When I first started writing iOS apps NSURLConnection was the sane predmoninant means for network communication. Creating a request object with nearly 100 square brackets was part of the norm. Eventually through working with others I found myself creating Singletons or classes with static functions to manage that minutiae. I wanted to carry this over to my new projects and was shocked at how much the world had changed, but in some ways remained the same. Replace a protocol based delegate class with a simple callback and Voila! Network Manager.

class NetworkManager: NSObject {

// Should add a check for network reachability
static func get(url:String, completionHandler: @escaping (Data?, URLResponse?, Error?) -> ())
// URL needs to be properly formatted
guard let requestURL = URL(string: url) else {
print("ERR: URL")

// Create the URL request
var request = URLRequest(url: requestURL)
request.httpMethod = "GET"

URLSession.shared.dataTask(with: request) { data, response, error in
do {
completionHandler(data, response, error)

There is a fair amount going on in those eleven or so lines of code, but from the top the get function expects a string url and a completion handler for the eventual items returned from the URLSession object. Portion of the world changing I mentioned earlier is with URLSession. NSURLConnection was deprecated along with skeuomorphism around iOS 7 and URLSession has been a steady hand since. It’s usage is simple enough: First, create a Request object. Second, pass that object into a shared instance of URLSession. Third, handle the output of the shared instance’s data task function. I pass this along to the completion handler that was passed initially to the function.

From there it is a matter of attaching a decoder to create the objects needed for the UI to represent. This is another world move that is close but not quite the same as before. Gone are a few classes cobbled together by the parsing glue to be replaced by wonderful Codable structs and Swift’s magic. Under the covers it is still KVP that transforms the json response from weird text to less weird text. At least it is not XML.