【问题标题】:Swift 2 Firebase TableViewSwift 2 Firebase 表视图
【发布时间】:2016-04-17 20:39:30
【问题描述】:

我是 swift 和 firebase 的新手,我正在尝试用 firebase 数据填充我的 tabelview。当我运行程序时,tableview 中没有显示任何内容。任何帮助将不胜感激。这就是我所做的,试图阅读文件,但它没有帮助。

import UIKit
import Firebase
import FirebaseUI


class ChurchTableViewController: UITableViewController {


let firebase = Firebase(url:"https://.....com/")

var items = [NSDictionary]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
     //self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func viewDidAppear(animated: Bool) {

    //MARK: Load data from firebsr
    firebase.observeEventType(.Value, withBlock: { snapshot in
        print(snapshot.value)
        }, withCancelBlock: { error in
            print(error.description)
    })

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return items.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let dict = items[indexPath.row]
    cell.textLabel?.text = dict["ChurchName"] as? String

    return cell
}

【问题讨论】:

  • 下载后运行这个命令 tableview.reloaddata()
  • 可能你的网址有误?
  • 这方面有一个很好的教程,正确的HERE

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

您已经为 Firebase 数据库中的某些值更改创建了观察者,但在您的闭包中您需要添加新项目,当然还需要重新加载您的 UITableView 以同步应用中的数据,请参见以下代码查看如何使用示例数据类型执行此操作的示例:

var items = [GroceryItem]()

override func viewDidAppear(animated: Bool) {
     super.viewDidAppear(animated)

     firebase.observeEventType(.Value, withBlock: { snapshot in
        var newItems = [GroceryItem]()

        for item in snapshot.children {
          let itemType = GroceryItem(snapshot: item as! FDataSnapshot)
          newItems.append(itemType)
        }

        // update your item with the new ones retrieved
        self.items = newItems

        // reload the data
       self.tableView.reloadData()
    })
}

在下面的结构中,您可以看到如何从 Firebase 返回的数据创建数据类型的示例

杂货项目

struct GroceryItem {

   let key: String!
   let name: String!
   let addedByUser: String!
   let ref: Firebase?
   var completed: Bool!

   // Initialize from arbitrary data
   init(name: String, addedByUser: String, completed: Bool, key: String = "") {
     self.key = key
     self.name = name
     self.addedByUser = addedByUser
     self.completed = completed
     self.ref = nil
   }

   init(snapshot: FDataSnapshot) {
     key = snapshot.key
     name = snapshot.value["name"] as! String
     addedByUser = snapshot.value["addedByUser"] as! String
     completed = snapshot.value["completed"] as! Bool
     ref = snapshot.ref
   }
}

要更深入地了解如何使用 Firebase,您可以阅读这个非常好的教程:

希望对你有所帮助。

【讨论】:

  • 感谢您的回复,itemType 是 NSDictionay。每当我用你给我的东西替换它时,我都会在 ---> let itemType = NSDictionay(snapshot: item as!FDataSnapshot) 处收到错误。错误说(参数标签'(快照:)'不匹配任何可用的重载)
  • @IamWayne 这只是一个示例,当然您需要从中创建数据类型,请参阅我的更新答案以通过创建数据类型的方式更好地理解答案
【解决方案2】:

检查您是否已正确设置 Tableview 的委托和数据源,为此,请转到界面构建器,cmd + 右键单击​​您的 tableview 并拖动到界面构建器中的黄色标题图标。

您应该看到两个选项,“datasource”和“delegate”,确保它们都被选中,然后重新运行您的应用程序,您应该看到表格填充了您加载的任何数据

【讨论】:

    【解决方案3】:

    你有三个问题

    1) 您没有为表格视图填充数据源。这通常是一个存储在类中的数组,因为它是按 .value 的,所以您需要遍历这些值以获取每个子节点的数据

    2) 您正在通过 .value 进行观察。这将返回节点中的所有内容、所有子节点、它们的子节点等,因此您将无法直接将其作为字符串值读取,除非节点包含所有内容,如单个键:值对,否则它们都是键:value 对将被读取。

    3) Firebase 是异步的,因此在观察块中,您需要填充数组,然后重新加载 tableview

    解决办法如下:

    给定一个结构

    users    
        user_id_0
           name: "Biff"
        user_id_1
           name: "Buffy"
        user_id_2
           name: "Skip
    

    这是读取每个名称并填充名称数组的相关代码

    var namesArray: [String] = []
    
    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
            for child in snapshot.children {
               let name = child.value["name"] as! String
               namesArray.append(name)
            }
            self.myTableView.reloadData()
    })
    

    用您的 items 数组替换 namesArray。

    他们的关键是让 Firebase 在告诉 tableView 刷新之前异步加载数据,并且在使用 .Value 时,确保使用 snapshot.children 遍历该节点中的所有子节点

    【讨论】:

      【解决方案4】:
      • 这是因为您的items 数组中没有数据。因此,首先在 viewDidAppear 方法中,您需要将 Firebase 数据字典附加到 items 数组中,然后调用 tableView.reloadData()
      • 还要检查您的 Firebase 数据库 URL 是否正确,您需要在附加到 items 数组时以正确的格式获取和存储数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多