我想从用户阵列获取姓名和电子邮件,但我收到错误"输入任何内容?没有下标成员"
NewMessController.swift中的
class NewMessagesViewController: UITableViewController {
let cellID = "cellId"
var user = [Users]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))
fetchUser()
}
func fetchUser(){
let rootRef = FIRDatabase.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "name")
query.observe(.value) { (snapshot) in
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
if let value = child.value as? NSDictionary {
let user = Users()
let name = value["name"] as? String ?? "Name not found"
let email = value["email"] as? String ?? "Email not found"
user.name = name
user.email = email
self.user.append(user)
DispatchQueue.main.async { self.tableView.reloadData() }
}
}
}
}
@objc func handleCancel(){
dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return user.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellID)
let user = Users[indexPath.row]
cell.textLabel?.text = user.name //error here
return cell
}
}
并在Users.swift中 导入UIKit
class Users: NSObject {
var name:String?
var email:String?
}
如何修复它并获取名称和电子邮件?非常感谢。
答案 0 :(得分:0)
尝试回复userData.value(forKey: "name") as? String
。
func fetchUser(){
let rootRef = FIRDatabase.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "name")
query.observe(.value) { (snapshot) in
DispatchQueue.main.async {
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
if let userData = child.value as? NSDictionary {
let user = Users()
let name = userData.value(forKey: "name") as? String ?? "Name not found"
let email = userData.value(forKey: "email") as? String ?? "Email not found"
user.name = name
user.email = email
self.user.append(user)
}
}
self.tableView.reloadData()
}
}
}