Filip Bellander
Filip Bellander

Reputation: 53

Make a list of firebase users

I am trying to make a list of all my users from Firebase with their username.

This is how my users is saved.

My problem is that I am trying to make an array of all the users.

import UIKit
import Firebase

var memberRef = Firebase(url: "\(BASE_URL)/users")
//var currentUser = DataService.dataService.USER_REF.authData.uid



var currentUsers: [String] = [String]()

class dataTableView: UITableViewController
{

    override func viewDidLoad()
    {
        loadUsers()
    }

    func loadUsers()
    {
        // Create a listener for the delta additions to animate new items as they're added
        memberRef.observeEventType(.ChildAdded, withBlock: { (snap: FDataSnapshot!) in

            print(currentUsers)

            // Add the new user to the local array
            currentUsers.append(snap.value as! String)

            // Get the index of the current row
            let row = currentUsers.count - 1

            // Create an NSIndexPath for the row
            let indexPath = NSIndexPath(forRow: row, inSection: 0)

            // Insert the row for the table with an animation
            self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top)

        })
    }

But I get the error cant cast value of type NSDictionary to NSString.

Upvotes: 0

Views: 404

Answers (1)

Jay
Jay

Reputation: 35677

The Firebase snapshot is a dictionary, not a string which is why you are receiving that error.

To access the elements of the snapshot:

if let name = snapshot.value["name"] as? String {
   print(name)
}

you can also use

if let name = snapshot.value.objectForKey("name") as? String {

Upvotes: 1

Related Questions