210

Share

APP DEVELOPMENT

How do Completion Handlers work In Swift?

  • Home
  • Blogs
  • How do Completion Handlers work In Swift?

A completion handler works as a callback function. A function that gets called back when a task is completed. It is passed as an argument into another function.

Somish Kakadiya

July 8, 2022

Many times, you are dealing with the web API and asynchronous tasks in your project. But you may get confused while working with the completion handler in Swift. In this blog, you will learn how to work with a Completion Handler.

What Is A Completion Handler?

It is the closure type block that you can call like a function, even also in the function, and perform your end block execution. It sounds like something complex, then let's see how it looks.

Why We Need To Use Completion Handler?

Before starting to look technical and syntax part, let’s talk about what it means to use completion handlers. Assume the user is updating an app and you definitely want to prompt that where is the update is reached. Also you possibly want to pop up a box that says, "Congratulations, application updated successfully. Now you may enjoy this perfectly!"

So how it is possible to perform execution at the end?

Completion Handlers :

Well, I am sure that you have already seen this concept,

The completion parameter says you give values to a closure block whose type is () -> () or () -> Void.

Here, () -> () requires no argument, and you may just print “Done” or anything you want that will show only after the transition has been completed. You can make it more even shorter using a trailing closure, like this :

Define Completion Handler :

Now let's design a handler who satisfy the above concept. So imagine you are a worker, and you have lot of work to do and want to say to your boss that, you will go home only after complete all your work.

Design Stuff Block : -

So first, let’s create a closure block whose type is (Bool) -> (). When you pass true, it will print something,

And you will call the handler like,

You can also use shorters like this,

Design Function Block :-

So this is the block which contains all that stuff or your work what you going to do, and after only you can go home. So once you complete all work you are going to call this handler with true value, to say your boss that "You are done and you are leaving the place".

The function will take a parameter as an argument whose type is (Bool) -> Void or you can say (Bool) -> (). As you may have guessed, we are going to pass workHandlerBlock.

To show that you are working really hard, we are going to call a for in loop. Once the loop is done, you will call, the harworkhandlerblock().

Only after you’ve done working, you are going to call enterDoStuff(true) which is eventually you are passing true tohandlerBlock. And when you call hardWorking() function,

And result will look like,

And yes, of course, you use shoter directly withput create a fake parameter,

Shorter Version: -

And here is the shorter version of this code, that you can pass the handle to the function directly, using trailing closure,

So, this is how easily you can set the handler or completion handler which you can call automatically when your execution code is totally complete and can perform your ending execution.

Scenario:-

Now imagine you are playing the music player in your application. Like this,

 

 

And the music player looks like,

 

 

And you are showing the bottom music player view to the other screen, like this.

 

 

So, here you need the handle play pause and stop music action to all screen.

To stop music action create define handler in your bottom music view file,

And for call this handler where you need, that means we need it at stop button clicked, so it will look like,

Then I've created a global variable for that bottom music view file :

Here is the code for getting view nib :

And for last I've just set up this handler definition at all view controller's where I need to show music bottom view and need to handle stop music action,

Another Way To Use Completion Handler:-

This is usually we used for define session, data task and API call and this is how the function takes a completion handler :

It has taking two arguments, UrlRequest and completionHandler : @escaping (Data?, URLResponse?, Error?) -> Swift.Void.

The second argument as we know its a closure that giving the values (Data?, URLResponse?, Error?) as arguments and returns nothing (Swift.Void).

And this is how we would call this function :

If closure is the last argument of the function, then we can use trailing closure syntax and just write the closure definition after the rest of or back of the function call :

Here another one scenario, you can use the completion handler :

Here you can see the function for reloadTabelview , and in the function definition, it's calling another function with name GettingData() and completion handler as an argument.

As we can see that function calls using trailing closure, closure definition direct back to function calls.

And then in definition of gettingData() it takes one parameter a handler :

GettingData(completionHandler: @escaping ([Item]?, Error?) -> Void

And the use of the completion handler has happened in the handler of datatask, one for if response got an error then it passing error and if response perfect data passing items as response.

And this completion handler calling will be executed as they define at its calling time. This is simply how we can use handler another way.

What Is @Escaping And @Nonescaping CompletionHandler?

You can see that inside the function block type is escaping without it is non-escaping default.

So what is the main and important difference between these both? And what for performing any asynchronous tasks inside the function, like working with URlSession or Datatask, or using GCD blocks for executing operations, or using Coredata and SQL database tasks?

In this case, the compiler will show you the error so that you can fix it by adding escaping.

 

 

I hope you enjoy this piece. So try it, and crack the code.

Conclusion:

This blog will help you a lot while working with the completion handler in Swift. It is useful to deal with asynchronous functions, and your code can continue to the next task when the asynchronous code runs in the background. Try and start developing your applications for clients.

 

img

Somish Kakadiya

CTO of Vasundhara Infotech, a leading Software development company in the USA. His technological interests has helped the company in making useful decisions.

message

Have a project in mind? Drop a message to Bansi Pipaliya & start the discussion!

Get a Newsletter

Sign Up to our newsletter to get latest updates staight in your inbox.

Vasundhara respects your privancy. No Spam!

Get a Newsletter

Sign Up to our newsletter to get latest updates staight in your inbox.

Vasundhara respects your privancy. No Spam!

message

Have a project in mind? Drop a message to Bansi Pipaliya & start the discussion!

Latest 13 Web Development Trends To Expect In 2022
April 11, 2022 Category : company news

Revealing Vasundhara’s New Identity

Read More
Leave a Comment