如何在TableView中显示Firebase数据?

时间:2016-08-30 10:37:50

标签: ios swift firebase tableview firebase-realtime-database

我需要帮助我可以从firebase获取数据但是我想在tableview中显示它可以帮助我吗?这是我的代码:

import UIKit
import Firebase
import FBSDKLoginKit
import FirebaseAuth

class ViewController: UIViewController, FBSDKLoginButtonDelegate {

    let loginButton: FBSDKLoginButton = {
        let button = FBSDKLoginButton()
        button.readPermissions = ["email"]
        return button
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getDataFireBase()
        view.addSubview(loginButton)
        loginButton.center = CGPointMake(160, 500)
        loginButton.delegate = self
    }
    // get data
    func getDataFireBase() {
        FIRDatabase.database().reference().child("Categories").observeEventType(.ChildAdded, withBlock: { (snapshot) in
            print(snapshot)
            }, withCancelBlock: nil)
    }

}

1 个答案:

答案 0 :(得分:2)

这是表格视图的一个例子:

import UIKit
import Firebase


    var bookList = [Book]()
    let ref = FIRDatabase.database().reference().child("Books")


 override func viewDidLoad() {
        super.viewDidLoad()
        retrieveBooks()
    }


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.bookList.count

    }

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

        var book = Book()

        book = bookList[indexPath.row]

        cell.user_name.text = book.user_name
        cell.book_title.text = book.book_title
        cell.book_author.text = book.book_author
        cell.book_price.text = book.book_price! + "€"

        cell.user_name.textColor = UIColor(red: 114 / 255,
                                          green: 114 / 255,
                                          blue: 114 / 255,
                                          alpha: 1.0)
        return cell
    }


 func retrieveBooks(){
        ref.queryOrderedByChild("book_price").observeEventType(.ChildAdded, withBlock: {
        (snapshot) in


            if let dictionary = snapshot.value as? [String:AnyObject]{

                let book = Book()

                book.setValuesForKeysWithDictionary(dictionary)

                    self.bookList.append(book)
                    dispatch_async(dispatch_get_main_queue(), {
                        self.tableView.reloadData()
                    })


            }
        })
    }

显然我有自定义单元格和自定义图书