无法从JSON Array Firebase

时间:2016-07-30 12:02:38

标签: ios json swift

语言:Swift 3.0 --- IDE:Xcode 8 ---项目:Firebase TableView

我想从Firebase数据库中检索数据。这是我的JSON数据库:

enter image description here

当我尝试获取firstName时,我得到的错误是lldb,这意味着没有这样的值。我认为问题是这个代码没有进入0,1,2这些"对象"与价值观,我不知道如何到达那里。

这是我的代码,我尝试检索数据并将它们加载到TableViewController上:

import UIKit
import Firebase

struct employee {
    let firstName: String!
    let lastName: String!
}

class TableViewController: UITableViewController {

    // MARK: Properties
    var rootRef: FIRDatabaseReference!
    var employees = [employee]()

    override func viewDidLoad() {
        super.viewDidLoad()

        rootRef = FIRDatabase.database().reference()
        rootRef.child("employees").queryOrderedByKey().observe(.value, with: { (snapshot) in
            let firstName = snapshot.value!["firstName"] as! String
            let lastName = snapshot.value!["lastName"] as! String

            self.employees.insert(employee(firstName:firstName,lastName:lastName), at: 0)
            self.tableView.reloadData()
        })
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for:
            indexPath) as! TablevieCell

        let employee = employees[indexPath.row]

        cell.firstNameLabel.text = employee.firstName


        return cell

    }

}

我希望有人告诉我如何在JSON上的数组中插入我的对象,如果这是问题或以任何方式帮助我。感谢

修改

print(snapshot.value)print:

Optional(<__NSArrayM 0x610000055750>(
{
    firstName = John;
    lastnName = Doe;
},
{
    firstName = Anna;
    lastnName = Smith;
},
{
    firstName = Emma;
    lastnName = Jackson;
}
)
)

0 个答案:

没有答案