Search code examples
jsonswiftasynchronousdispatch-asynccompletion

-- swift: async + JSON + completion + DispatchGroup


The code in my viewcontroller-class is executed before the JSON-download-process is ready even though there is a completion handler in the func for downloading JSON an a DispatchGroup(). I store the JSON-data in an array called "fetchedModules" and this is filled with 11 items in this case. Why does this happen?

result in console:
---> in Class PostCell - func numberOfSections: 0
JSON call finished 

// ViewController
override func viewDidLoad() {
    super.viewDidLoad()

    let group = DispatchGroup()

    group.enter()

    self.fetchJSON()
    // here calling downloadJSONasync

    group.leave()

    group.notify(queue: .main)  {
        print("JSON call finished")
    }

    ...

    // networkService with completion
    func downloadJSONasync(searchItem: String, completion: @escaping ([NSDictionary]) -> Void) {

    //request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData

    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    //let session = URLSession(configuration: configuration, delegate: nil)

    let session = URLSession(configuration: configuration)

    let task = session.dataTask(with: request, completionHandler: {(data, response, error) in

        guard let data = data, error == nil else { return }

        if (error != nil) {
            print("error!")
        }

        else{

            do {

                let fetchedData = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [NSDictionary]

                completion(fetchedData)

            }

            catch {
                print("error")
            }

        }

    })

    task.resume()

}

// call in viewController
override func numberOfSections(in tableView: UITableView) -> Int {

    print("---> in Class PostCell - func numberOfSections: \(String(describing: fetchedModules.count))")
    return fetchedModules.count

// code of fetchJSON
func fetchJSON()
{

    let baseurl = AppConstants.Domains.baseurl // https://m.myapp2go.de

    let compositURL = baseurl + "getmodules_noItems.php?id=\(AppConstants.appString.startString)"

    let encodedUrl : String! = compositURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) // remove the spaces in the url string for safty reason

    let JSONurl = URL(string: encodedUrl)! // convert the string into url

    var JSONrequest = URLRequest(url: JSONurl) // make request

    JSONrequest.httpMethod = "GET"

    //JSONrequest.cachePolicy = .reloadIgnoringCacheData

    let networkService = NetworkService(request: JSONrequest)

    networkService.downloadJSONasync(searchItem: AppConstants.appString.startString, completion: { (fetchedData) in

        fetchedModules.removeAll()

        DispatchQueue.main.async {

            for eachFetchedModul in fetchedData {

                let eachModul = eachFetchedModul

                if

                    let custid    = eachModul["custid"]    as? String,
                    let modulcat  = eachModul["modulcat"]  as? String,
                    let modulname = eachModul["modulname"] as? String,
                    let comment   = eachModul["comment"]   as? String

                {

                    fetchedModules.append(CModules(custid: custid, modulcat: modulcat, modulname: modulname, comment: comment))

                    print(custid)
                    print(modulcat)
                    print(modulname)
                    print(comment)

                    print("---------------------")
                }

            }// for end

            // ... somehow set data source array for your table view
            self.tableView.reloadData()
        }// dispatch



    }


)} // func end

Solution

  • Because fetchJSON returns immediately, before the JSON is downloaded. The effect is that the DispatchGroup is entereed and left right away, without waiting for the JSON:

    group.enter()
    self.fetchJSON() // returns immediately
    group.leave()    // the JSON has yet to be downloaded
    

    To wait until the JSON has arrived, add a completion handler to fetchJSON:

    override func viewDidLoad() {
        group.enter()
        self.fetchJSON { 
            group.notify(queue: .main)  {
                print("JSON call finished")
            }
            group.leave()
        }
    }
    
    // Change the data type of the completion handler accordingly
    func fetchJSON(completionHandler: @escaping (Data?) -> Void) {
        // ...
        networkService.downloadJSONasync(searchItem: AppConstants.appString.startString) { fetchedData in
            defer { completionHandler(fetchedData) }
            // ...
        }
    )
    

    Using defer ensures that the completion handler will always be called, no matter how the outer closure returns. I'm not clear why you use a DispatchGroup here as there is no waiting, but I kept it in place to answer your question.