How to use Completion Handler in Swift

JSON Networking

Posted on 26 Aug 2023 . 2 min read


To know when a network request has been successfully completed while retrieving data from the web, completion handlers must be created. When carrying out lengthy operations, it comes in helpful.


You must learn how to hit an API and parse json data before reading any further in this article.


Syntax


func fetchData(completion: @escaping () -> Void) {
     completion()
}


Although at first glance it appears complex, we have simplified the fetchData() function.

  • parameter of completion is taking escaping closure
  • escaping keyword means that closure will executes when function returns


Here is another example that completion takes String parameter.

func fetchData(completion: @escaping (String) -> Void {
     completion(result)
}


In another article, we learned how to fetch Flickr API data and decode it using JSONDecoder. We will now add a completion handler to the network request for the Flickr API.

func fetchData(completion: @escaping (FlickrImageInfo) -> Void {

let url = URL(string:"https://api.flickr.com/services/rest/?method=flickr.
photos.search&api_key=526ada5ee1ea2cf61ac6bd3d3d2f405e&tags=kitten&page=0&
format=json&nojsoncallback=1")!

let task = URLSession.shared.dataTask(with: url) {
  (data, response, error) in

  let jsonDecoder = JSONDecoder()
  if let data = data,
      let result = try? jsonDecoder.decode(FlickrImageInfo.self, from: data) {
        completion(result)
  }
}

task.resume()

}


We will now call the function and print the outcome.


fetchData { (result) in
   print(result)
}


The main issue with this code is that it does not account for any failures, such as when there is no response or when JSON cannot be decoded.


So to handle this situation we have to address errors using Result enum. It has two cases success or failure.


The bottom line


func fetchData(completion: @escaping (Result<FlickrImageInfo, Error>) -> Void {
    ……
}


Make necessary changes to the previous code sample.

func fetchData(completion: @escaping (Result<FlickrImageInfo,Error>) -> Void {

let url = URL(string:"https://api.flickr.com/services/rest/?method=flickr.
photos.search&api_key=526ada5ee1ea2cf61ac6bd3d3d2f405e&tags=kitten&page=0&
format=json&nojsoncallback=1")!

let task = URLSession.shared.dataTask(with: url) {
  (data, response, error) in

  let jsonDecoder = JSONDecoder()
  if let data = data {
      do {
      let result = try jsonDecoder.decode(FlickrImageInfo.self, from: data)
        completion(.success(result))
      } catch {
        completion(.failure(error))
      }
  }
}

task.resume()

}


Last make changes while calling that function.

fetchData { (result) in
  switch result {
    case .success(let info):
       print(info)
    case .failure(let errror):
       print(error)
  }
}


The bottom line


It takes some practice to understand these patterns, but once you do, it becomes simple.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.


Thanks!


More articles:


Share this article



Written By

Generic placeholder image

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me for more updates:


Discover articles by topics

SwiftUI Class Struct Networking XCode NSCache Enum Optionals Property Observers Closures Guard Reviews StoreKit App Store Algorithms Testing Operators Protocol Extensions Weak Unowned SwiftData WWDC23 GCD API Admob SwiftLint Lottie Foreach Objective-C UIKit NavigationSplitView

Related Articles


Integrating SwiftUI with UIKit Using UIHostingController

With the introduction of SwiftUI, Apple has provided developers with a modern way to build user interfaces across all Apple platforms....

2024-07-09 . 3 min read     UIHostingController

Read More »

Deep Dive into Autorelease Pools in Swift

In the realm of software development, memory management plays a crucial role in ensuring the efficient allocation and deallocation of memory...

2024-01-28 . 4 min read     Swift Autorelease

Read More »

Swift enum equatable: with or without associated values

Swift enums provide a powerful way to model a set of related values. Enums can be equipped with associated values, allowing them to represen...

2024-01-24 . 3 min read     Swift Enums

Read More »

How to create Date Picker in SwiftUI

Use a DatePicker when creating a view that enables users to choose both a calendar date and, if needed, a specific time.In SwiftUI, you can ...

2024-01-16 . 2 min read     SwiftUI DatePicker

Read More »

Getting started with Swiftlint to enforce Swift style

SwiftLint is a tool that ensures Swift code adheres to defined style guidelines. It automates code review by identifying and suggesting impr...

2023-12-29 . 4 min read     Swift SwiftLint

Read More »

How to use Lottie animation in SwiftUI

Lottie is a fantastic tool for incorporating high-quality animations into your SwiftUI projects. There are several ways to add Lottie to pro...

2023-12-13 . 2 min read     SwiftUI Lottie

Read More »