如何在我的iOS Swift listview控制器中显示Firebase信息?

问题描述:

我很难将Firebase加入我的控制器。由于我能够打印到控制台,Firebase工作正常。我需要能够在我的应用程序中显示所有数据。请协助! // // All.swift //保证性定价 //如何在我的iOS Swift listview控制器中显示Firebase信息?

enter image description here

import Foundation 
import UIKit 
import Firebase 

class All: UINavigationController, UITableViewDataSource, UITableViewDelegate { 

var items: [String] = [] 
var tableView: UITableView! 
let cellIdentifier = "CellIdentifier" 

override func viewDidLoad(){ 
    super.viewDidLoad() 

    self.tableView = UITableView(frame:self.view!.frame) 
    self.tableView!.delegate = self 
    self.tableView!.dataSource = self 
    self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) 
    self.view?.addSubview(self.tableView) 

    let ref = Firebase(url:"https://sizzling-inferno-451.firebaseio.com/services") 
    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in 
     for child in snapshot.children { 

//    let key = child.key //returns -Jikaijsipaij and -kalksdokoas 
//    let name = child.value.objectForKey("service_name") as NSString? 
////     
//    self.items.append(key) 
     } 
     // do some stuff once 
     print(snapshot.value) 

     // get these values and put them in the cell's text view. key is more important 
     print(snapshot.key) 



     // add to the array and just this array 


     self.tableView!.reloadData() 
    }) 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return items.count 
} 


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

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

    // Fetch Fruit 
    let fruit = items[indexPath.row] 

    // Configure Cell 
    cell.textLabel?.text = fruit 
    return cell 
} 

// onclick printing 
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    print(items[indexPath.row]) 
} 

}

+0

嗯,首先你是不是填充项目阵列(这是tableView数据源)与任何数据。你会想在ref.observe块中做到这一点。它看起来像你的代码被注释掉,你应该使用,至少如果你只是想显示一个键列表。哦,并且您的Firebase结构中不包含任何名为service_name的键,因此您应该使用存在的键名称,例如小时或输入 – Jay

+0

那么我注释的代码我试图从一个Firebase结构中建模。我最终试图实现它,但我使用描述而不是service_name。出于某种原因,我不断收到一个错误,说“可选类型的值AnyObject?!”不打开;你的意思是使用'!'?'要么 '?' “。另外,你有什么建议如何填充数组?或者有什么想法发生了什么错误? Firebase工作正常,我的控制器设置正确......我一直在处理这个错误一段时间,我不知道如何解决它。 –

+0

您应该阅读optionals(?),因为它们是Swift的一个组成部分 - 有关变量和optionals的Apple教程非常好。我添加了一个应该提供一些帮助的答案。 – Jay

这里有一个快速片断来填充块内的阵列,然后一旦填充重新加载tableview以显示数据。

user_id_0 
    name: "Fred" 
    friend: "Barney" 

和代码中的所有用户的阅读,在它们之间迭代和提取每个名称,并将其添加到一个数组:

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() 
    })