Completion Handler in Swift 4.2

Getting started with Completion Handlers (Block syntax) in Swift. Mainly we most of the time dealing with the Web API and other asynchronous tasks inside our projects. How to make it a better way with the help of blocks.

We have seen so many time this code-

URLSession methods
Let’s see after writing code-
URLSession code for url request
Inthe above code we are calling web url with the help of URLSession.Now how to handle this code after getting response inside this block.if we have to pass it or return it in another function without using any global variable and other function. How we can do it 🤔

Let’s see How to create Blocks. 😎

Write your own completion block -
func requestForUserDataWith(_ parameters: [String: String], completionHandler: (_ result: [String: Any], _ error: Error) -> Void){     //.. Code process
}
Now how it will return us data in this function after executing operations in main task.
func requestForUserDataWith(_ parameters: [String: String], completionHandler: (_ result: [String: Any], _ error: Error) -> Void){     //.. Code process 
     
completionHandler(result, error) // return data & close 
}

How to use it- 🤔

Your code will look like this when you will call the function.
requestForUserDataWith(parameters) { result, error in     //.. Code process
}

Try with other things & make it more advance 🚀

ImageProvider class, for example, using here for Completionhandler. It will download image Asynchronously from the image URL.
struct ImageProvider: RequestImages {fileprivate let downloadQueue = DispatchQueue(label: "Images cache", qos: DispatchQoS.background)//MARK: - Fetch image from URL and Images cache
func 
loadImages(from url: URL, completion: @escaping (_ image: UIImage) -> Void) {   
downloadQueue.async(execute: { () -> Void in
      do
{         let data = try 
Data(contentsOf: url)
         
if let image = UIImage(data: data) {
            
DispatchQueue.main.async { completion(image) }
         } 
else { print("Could not decode image") }
      
}catch { print("Could not load URL: \(url): \(error)") }   
})  
}
}protocol RequestImages {}  extension RequestImages where Self == ImageProvider{  func 
requestImage(from url: URL, completion: @escaping (_ image: UIImage) -> Void){
     //calling here another function and returning data completion     loadImages(from: url, completion: completion) 
  
}
}
We calling function for downloading images with the help of other request function by using CompletionHanlder. Below code we can see how it will work for us.
let imageProvider = ImageProvider() imageProvider.requestImage(from: url) { image in   //code process
}

Now, What is @escaping and @nonescaping CompletionHandler? 🤔

If you have seen my code where I have used loadImages, inside this function block type is escapingAfter Swift 3.0 version by default blocks ( in Swift closures) are non-escaping. So what is the main difference between these?
And performing any 
Asynchronous Tasks inside the function like URLSession or using GCDblocks for executing any operations, storing offline data in SQL or Core data. In this case, it will show you the error for fixing it. It will not accept non-escaping type block. You have to fix it by using escaping block.
@escaping closure

Conclusion

In this part, you got understanding for how to create your own completionHadler block syntax in the Swift. This is pretty easy for performing Asynchronous code inside your project. Now you got understanding how to manage function with return type with the use of blocks. After that how to use it inside your code. This will make your work more easy and you can make any methods or wrapper with the help of Block syntax. Let’s talk about the example which you can make inside your project for performing web API calling and Store Database operations, you can make the wrapper for it. 🎉
I have also covered in this part advance uses of completionHadler. Now you got understanding for escaping and non escaping blocks. I hope you enjoyed this part. 😊✌🏼

Comments

Popular Posts