单元格不显示任何内容,但print(字典)显示正确的信息。所以我得到了正确的信息
这是我的代码:
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAnalytics
class VCTableViewController: UITableViewController {
var ref: DatabaseReference!
var refHandle: UInt!
var requestList = [request]()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
ref = Database.database().reference()
fetchUsers()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for:indexPath)
// let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
cell.textLabel?.text = requestList[indexPath.row].name
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requestList.count
}
func fetchUsers() {
refHandle = ref.child("Request").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
print(dictionary)
let request1 = request(dictionary: dictionary)
// request1.setValuesForKeys(dictionary)
self.requestList.append(request1)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
}
}
我的请求swift文件:
import Foundation
class request: NSObject {
var request: String?
var name: String?
var longitude: String?
var latitude: String?
init (dictionary: [String: Any]) {
super.init()
request = dictionary["request"] as? String
}
}
答案 0 :(得分:0)
试试这个:
class request: NSObject {
var request: String?
var name: String?
var longitude: String?
var latitude: String?
init (dictionary: [String: Any]) {
super.init()
name = dictionary["name"] as? String
longitude = dictionary["longitude"] as? String
latitude = dictionary["latitude"] as? String
}
}
但是有更好的方法来反序列化。看看Codable。
这是一个可以让你思考未来的例子:
//Codable protocol is for both Encoding & Decoding
struct Location: Codable {
let name: String
let longitude: String
let latitude: String
}
//Encode to json format from struct
let location = Location(name: "my location", longitude: "-94.420307", latitude: "44.968046")
if let encoded = try? JSONEncoder().encode(location) {
if let encodedJSON = String(data: encoded, encoding: .utf8) {
print(encodedJSON)
//Prints: {"name":"my location","longitude":"-94.420307","latitude":"44.968046"}
}
}
//Decode from json data to struct
let jsonStr = """
{
\"name\": \"my location\",
\"longitude\": \"-94.420307\",
\"latitude\": \"44.968046\"
}
"""
//jsonData is of type Data? which is generally what comes back from http request.
if let jsonData = jsonStr.data(using: .utf8) {
if let decoded = try? JSONDecoder().decode(Location.self, from: jsonData) {
print(decoded.name, decoded.longitude, decoded.latitude)
//Prints: "my location -94.420307 44.968046"
}
}