从Firebase检索名称到表格视图

时间:2016-04-13 15:11:32

标签: ios xcode swift firebase tableview

这是iOS应用程序的仪表板:

{
"users" : {
"0b71693a-4f16-4759-acd6-706da1a466a0" : {
  "Picker" : "Jubail",
  "details" : "iOS second",
  "name" : "Huda"
},
"16b13b1e-0025-4eee-a590-5bbacc52071c" : {
  "Picker" : "Jeddah",
  "details" : "Hellom from the Internet",
  "name" : "Rania"
   },
 "394b6555-1838-4565-87ac-e423c3b89cf1" : {
  "Picker" : "Jubail",
  "details" : "",
  "name" : "Marwa"
},
         }
}

我正在尝试将其选择器为Jubail的所有用户的名称检索到表格视图单元格!

我是swift的初学者,我不知道怎么做! 我试过,这是我做的代码:

 import UIKit
class CookingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

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

let ref = Firebase (url: "https://mariahfinaltest.firebaseio.com")

@IBOutlet weak var CookingTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    ref.queryOrderedByChild("Picker").queryEqualToValue("Riyadh")
        .observeEventType(.Value, withBlock: { snapshot in
            for child in snapshot.children {
               self.BusinessName = child.value["name"] as! [String: String]
            }
            self.CookingTableView.reloadData()
        })
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5 //It should not be 5 here! How Can I make it as long as cells?
}


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

    let cell = self.CookingTableView.dequeueReusableCellWithIdentifier("CookingCell", forIndexPath: indexPath) as! CookingTableViewCell

    var keys: Array = Array(self.BusinessName.keys)
    cell.BusinessNameLabel.text = BusinessName[keys[indexPath.row]] as String!
    return cell

}
}

我一直都有错误! 我不知道出了什么问题!

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码非常接近

由于

,很可能会崩溃
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5 //It should not be 5 here! How Can I make it as long as cells?
}

这告诉你的tableView它有5个项目,如果它不会导致超出范围值并崩溃。

所以这里是简化的设计模式。

var namesArray: [String]

ref.queryOrderedByChild("Picker").queryEqualToValue("Riyadh")
    .observeEventType(.Value, withBlock: { snapshot in
        for child in snapshot.children {
           let name = child.value["name"] as! String
           self.namesArray.append(name)
        }
        self.CookingTableView.reloadData()
})

然后你的tableView委托方法

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return namesArray.count //return the number of items in the array
    }

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier("mycell", forIndexPath: indexPath) as! UITableViewCell
     let name = namesArray[indexPath.row]
     cell.textLabel?.text = name
     return cell
    }