如何在TableView中显示Firebase数据?

问题描述 投票:1回答:1

我需要帮助我可以从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)
    }

}
ios swift firebase tableview firebase-realtime-database
1个回答
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()
                    })


            }
        })
    }

显然我有一个自定义单元格和一个自定义Book类

© www.soinside.com 2019 - 2024. All rights reserved.