get back datas out of a dataTask method

Hello. For an internship, I have to do a swift application that get json datas from an API.

I believed I have achieved to get datas and store in an array, with dataTask, when I did a “print” from my dataTask in the console,

but when I try to do a “print” out of the dataTask, it ask me that my array is empty.


I have tried to think about that, but I can’t find exactly what I do wrong.


Maybe that it’s a problem of priorities, local/global variables or something like that ?


import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!

    var storageFurnitureArray:[String] = []


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


        return storageFurnitureArray.count




    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: “myCell”, for: indexPath) as UITableViewCell


        //cell.textLabel?.text = self.storageFurnitureArray[indexPath.row]


        return cell




    override func viewDidLoad() {






    func downloadJsonWithTask() {


        let url = URL(string: ““)!


        let session = URLSession.shared

        let request = URLRequest(url: url)


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


            guard error == nil else {




            guard let data = data else {




            do {

                //create json object from data

                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {


                    if let families = json[“families”] as? [[String:Any]] {


                        for family in families {


                            if let familyName = family[“familyName”] as? String {








                        /OperationQueue.main.addOperation {












            catch let error {













Powered by WPeMatico

You may also like...

Comments are closed.