Search code examples
iosjsonswiftuitableviewparse-cloud-code

Append JSON response to tableview -Swift


I'm calling a PFCloud function that returns a json response of user credit cards, I'd like to display some of the card data. I've got an array I tried to append to and it's failing to display. I called this function in viewDidLoad.

func loadCards(){

    if let customer = PFUser.currentUser()?.objectForKey("stripe_customer_id") as? String {

        PFCloud.callFunctionInBackground("listCards", withParameters: ["customerId": customer], block: { (success: AnyObject?, error: NSError?) -> Void in

            if error != nil {
                println(error)
            }
            else {
                let responseString = success as? NSArray

                    if let cardToDisplay = responseString!.valueForKey("cardId") as? NSArray{


                        println(cardToDisplay)
                        self.displayCards.addObject(cardToDisplay)


                    }

                self.tableView.reloadData()
            }

        })
    }

}



// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    println(self.displayCards.count)
    return self.displayCards.count

}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: CardsTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CardsTableViewCell

 self.displayCards[indexPath.row] = cell.card.text!
return cell
}

Here are my logs from the console:

0
0
0
0
0
0
(
"card_16v8teBnRIkk4qBepmuz2Mlk",
"card_16ymjoBnRIkk4qBeirtCdYdn",
"card_16ymfzBnRIkk4qBebvP4wwNO",
"card_16ymfzBnRIkk4qBeoRUVccws",
"card_16ymaPBnRIkk4qBeK2ju6ckP",
"card_16ylqyBnRIkk4qBeffUN2bwo",
"card_16ylq3BnRIkk4qBePGngNz8H"
)
1

Solution

    • You need to reload te tableView in main thread. As you got into background to make the request, you need to do:

      dispatch_async(dispatch_get_main_queue()) { () -> Void in
          self.tableView.reloadData()
      }
      

      Instead of just self.tableView.reloadData()

    • cardToDisplay appears to be an array, so change self.displayCards.addObject(cardToDisplay) to self.displayCards = cardToDisplay

    • The line self.displayCards[indexPath.row] = cell.card.text! in the cellForRowAtIndexPath should be the other way round.. You should set the text as the self.displayCards[indexPath.row] is. So it should be cell.card.text = self.displayCards[indexPath.row]