2016-04-13 27 views
0

我很難將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

回答

0

這裏有一個快速片斷來填充塊內的陣列,然後一旦填充重新加載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() 
    }) 
相關問題