Swift:从Firebase数据库中检索数据到标签

时间:2016-09-28 09:02:01

标签: swift uitableview firebase uilabel firebase-realtime-database

我试图将我的数据从Firebase数据库中获取到Swift中的特定标签。我在TableViewMain.storyboard)标记为12的标签中有两个标签。

ViewController中,我有以下代码:

import UIKit
import Firebase
import FirebaseDatabase

struct confStruct {
    let title : String!
    let place : String!
}

class EVS_Table_VC: UITableViewController {
    var conf = [confStruct]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let databaseRef = FIRDatabase.database().reference()
        databaseRef.child("conferences").queryOrderedByKey().observeEventType(.ChildAdded, withBlock: {
                    snapshot in

            self.tableView.reloadData()
        })
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return conf.count
    }

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

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

        let label1 = cell?.viewWithTag(1) as! UILabel
        label1.text = conf[indexPath.row].title

        let label2 = cell?.viewWithTag(2) as! UILabel  
        label2.text = conf[indexPath.row].place

        return cell!

    }      
}

但是模拟器中没有任何内容。有人提出如何解决这个问题吗?此结构confStruct初始化我的变量 数据库? (titleplace)。

JSON树:

"conferences": {
           "Key": {
              "date": "some date"
              "deadline": "some deadline"
              "place": "some place"
              "title": "some title"
                  }
               }

1 个答案:

答案 0 :(得分:0)

将您的结构更改为: -

   struct confStruct {
    let title : String!
    let place : String!

    init(title_String : String!, place_String : String!){

        self.title = title_String
        self.place = place_String
    }

}

和: -

  FIRDatabase.database().reference().child("conferences/Key").observeSingleEvent(of: .value, with: {(snap) in


        if let snapDict = snap.value as? [String:AnyObject]{

            let titleS = snapDict["title"] as! String
            let placeS = snapDict["place"] as! String

            let temp = confStruct.init(title_String: titleS, place_String: placeS)
            self. conf.append(temp)
            self.tableView.reloadData()
        }
    })