Ячейка в TableView не отображает информацию.стриж - PullRequest
0 голосов
/ 29 мая 2018

Ячейка ничего не отображает, но печать (словарь) отображает правильную информацию.Итак, я получаю правильную информацию

Вот мой код:

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
  }
}

1 Ответ

0 голосов
/ 29 мая 2018

Попробуйте:

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"
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...