I am using the code below to sync data with my server. After completing the task, I would like to call:
self.refreshControl?.endRefreshing()
However, I would like to make sure it happens after anything that might happen inside this method. Is this where I would use a completion handler? It is confusing to me because I am already running code that gets executed after getting the http response. If I add a completion handler, does it get executed after the http response is received? And could I put my endRefreshing() code there that would happen after anything that might happen in the code below? Thanks!
func syncCustomers(token: String) {
    let url:NSURL = NSURL(string: Constants.Api.BaseUrl + "api/customer")!
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url as URL)
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"
    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
        guard let data = data else { return }
        do {
            if error != nil {
                self.showAlert(title: "Error", message: error!.localizedDescription)
            }
            else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Array<Any>
                    DispatchQueue.global().async {
                        for item in json! {
                            if let customer = Customer(json: item as! [String : Any]) {
                                _ = SqliteDB.instance.replaceCustomer(customer: customer)
                            }
                        }
                        self.customers = SqliteDB.instance.getCustomers()
                        self.tableView.reloadData()
                    }
                } else if httpResponse.statusCode == 401 {
                    self.showAlert(title: "Error", message: "Unauthorized. Please try logging in again.")
                }
            }
        } catch let error as NSError {
            self.showAlert(title: "Error", message: error.localizedDescription)
        }
    }
    task.resume()
}