0
    import UIKit
import Firebase

class PendingVC: UIViewController,UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var myTableView: UITableView!

let ref = firebasehelper.firebaseURL()
var data = [[:]]




//MARK: vars
        var address:AnyObject!
        var postTitle:AnyObject!
    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.dataSource = self
        myTableView.delegate = self

//The example below work great I get the layout the way it should look, but i want to generate the dictionary from the firebase function below.

/*
     self.data = [
     [
     "firstname": "sallie",
     "lastname": "ammy"
     ],
     [
     "firstname": "jamie",
     "lastname": "brown"
     ]
     ]

     */

It should look something like this and i want to past the data to the table. Im not sure if i should be looping. the way it is below bring the following error "fatal error: unexpectedly found nil while unwrapping an Optional value" the variables are not nil when i print them i get data back.

ref.childByAppendingPath("backend/posts").queryOrderedByChild("requestFrom").queryEqualToValue(ref.authData.uid).observeEventType(.ChildAdded, withBlock: {snapshot in
                var firstname = snapshot.value["firstname"] as! String
                var lastname = snapshot.value["lastname"] as! String


         self.data = [
            [
                "firstname": firstname,
                "lastname": lastname
            ]
        ]



       print(self.data)
    })







}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! statusPrototypeCell


    let object = data[indexPath.row]



cell.firstname.text = object["firstname"] as! String
  cell.lastname.text = object["lastname"] as! String


    return cell
}


override func viewWillAppear(animated: Bool) {
    navigationController?.navigationBarHidden = false

    navigationController?.navigationBar.barTintColor = UIColor(red:0.4, green:0.76, blue:0.93, alpha:1.0)
    navigationController?.navigationBar.translucent = false
    self.title = "Signup"

    self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
}
}
SwiftER
  • 1,235
  • 4
  • 17
  • 40

2 Answers2

0

You are using Dictionary so it doesn't returning count value so better to use array like [] instead of [:]

One more thing You have forgot the following statement to include in ViewDidLoad method myTableView.delegate = self

  • @ramaKrisma i was able to place the dictionary to the table, the issue Im having now is generating the data I get a nil answer Im not sure why please take a look at the question edit. – SwiftER Apr 28 '16 at 13:49
0

While you can use a dictionary as a dataSource, it's unordered which means the items in your tableView will also be unordered. Using an array is a better solution. In fact, an array of dictionaries make a nice ordered data source.

Also, to clarify, you don't pass a dictionary or data to a tableView per your question. The tableView gathers it's data from a datasource via it's delegate methods

Assume the following Firebase data structure

"users" : {
    "uid_0" : {
      "first_name" : "Bill",
      "last_name" : "Nye"
    },
    "uid_1" : {
      "first_name" : "Leroy",
      "last_name" : "Jenkins"
    },
    "uid_2" : {
      "first_name" : "Peter",
      "last_name" : "Sellers"
    }
  }

and to populate an array of dictionaries:

var usersArray: [Dictionary<String, String>] = []

let usersRef = self.myRootRef.childByAppendingPath("users")

usersRef.observeEventType(.ChildAdded, withBlock: { snapshot in

  var userDict = [String:String]()
  userDict["key"] = snapshot.key
  userDict["firstName"] = snapshot.value["first_name"] as? String
  userDict["lastName"] = snapshot.value["last_name"] as? String         
  self.usersArray.append(userDict)
})

to access the data, use the keys you created above.

For example: to print the users in the array from a button

for userDict in self.usersArray {
    let key = userDict["key"]
    let fName = userDict["firstName"]
    let lName = userDict["lastName"]

    print("\(key!)  \(fName!)  \(lName!)")
}

Once you have an understanding of that, you can then use the usersArray to populate the tableView.

let userDict = usersArray[indexPath.row]
cell.firstname.text = userDict["firstName"] as! String
cell.lastname.text = userDict["lastName"] as! String

The tricky bit is loading the array with all of the data needed, then reload the tableView to display it. If you have a small set of data, .Value will work for that. A larger set of data requires another technique, see This Answer

Community
  • 1
  • 1
Jay
  • 34,438
  • 18
  • 52
  • 81
  • one thing i realize is that .ChildAdded kept returning the items nil. once i did change that to .Value I was able to get the data from Firebase. in the cellForRowAtIndexPath function I receive "fatal error: Index out of range" at the "let userDict = usersArray[indexPath.row]" – SwiftER Apr 29 '16 at 03:12
  • @peter That's because when you use .Value, it returns everything in that node; all child nodes, their children etc etc. With .Value you will need to iterate over the child nodes using *for child in snapshot.children*, and then build your dictionary from each *child* within that loop. After the loop concludes, call *tableView.reloadData* – Jay Apr 29 '16 at 12:29
  • everything work great until i try to place UserDict outside of the firebase closure into the tableview cellForRowAtIndexPath function. I tried to declare the variable outside of the firebase Function before I used it but no luck. I also trying to use the firebase function inside a function but once again it will be inside a closure so it will not work. Ive been pulling my hair out trying to figure this out but no luck. – SwiftER May 02 '16 at 17:04
  • @peter Why would you place UserDict outside of the firebase closure? Your **ARRAY** is what holds the data for the tableView. That array is a series of dictionaries. The array is defined outside the closure by this line var usersArray: [Dictionary] = [] and is populated with dictionaries inside the closure. The array will 'hang around' and can be accessed anywhere else within the class (or function depending on where you put it) – Jay May 02 '16 at 17:39