1

I have appended JSON into array and it shows blank when I print the array from viewdidload or somewhere else.

I have created a custom function for fetching data and called it in the viewdidload.

Following is my entire code:

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var Usernames = NSMutableArray()
    var emails = [String]()

    let url_Posts = "https://jsonplaceholder.typicode.com/posts"
    let url_Users = "https://jsonplaceholder.typicode.com/users"

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchJSONData()
        print("usernames are",(Usernames))
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

        return Usernames.count
    }

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

        //TableView Codes
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PostsCell
        cell.lblEmail.text = self.emails[indexPath.row]
        cell.lblUsername.text = self.Usernames[indexPath.row] as! String
        return cell
    }

    func fetchJSONData() {

        Alamofire.request(url_Users).responseJSON   {
        (response) in

            if let rawData = response.result.value as! [[String:Any]]? {

                for one in rawData {

                    let name = one["name"]
                   self.Usernames.add(name!)

                }
            }
        }
    }
}
Cal
  • 422
  • 6
  • 20

1 Answers1

0

You need to either write a completion like here Returning data from async call in Swift function

OR reload the table here

 for one in rawData {   
  let name = one["name"]
   self.Usernames.add(name!)
 }
 self.tableView.reloadData()

It's better also to have a model array instead of separate arrays and use Codable

struct Root : Decodable {
   let name,email:String
}

func fetchJSONData(completion:@escaping([Root]?) -> () ) {

     Alamofire.request(url_Users).responseData(completionHandler : { (response) in
    switch response.result {
    case .success( let data):
        // I want to append the user struct by the user data collected from JSON
        print(response.result.value!)
        do {
            let res = try JSONDecoder().decode([Root].self,from:data)
            completion(res)
        }
        catch {
            print(error)
            completion(nil)
        }

    case .failure(let error):
        print (error)
         completion(nil)
    }

  }) 
}

Call

fetchJSONData {  (arr) in

  if let res = arr {
    print(res)
  }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87