Methods with completion callback in iOS swift

Completion callbacks are important when we are doing some asynchronous task in the background and need to change the UI based on the response. I wanted to call an API with some parameters and as I had mentioned earlier I will update the UI based on this API response. It is possible to call the Api in the ViewController itself and update the UI. But MVC will not suggest the developer to do this. What I normally do is creating a swift file for all the API calls and get a completion callback when the response is received. May be we can also use delegates to do this. But here I use a completion callback.

Here is the playground code for calling a method which accepts a Dictionary as parameter and have two completion blocks.One for success and other one for failure. Success callback returns a parameter of type [Any] as it can be either an array or a Dictionary. The failure callback returns an error and the parameters passed. Feel free to run the code in playground and check the response.

Here I am pasting the console output also:

[AnyHashable(“key”): “value”]
Success. Response received…: [1, 2, 3, 4, 5]
Error: The operation couldn’t be completed. ( error 1.)
Parameters passed are: [AnyHashable(“key”): “value”]

Enjoy !

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!