Как добавить значение Firebase в табличном виде - PullRequest
0 голосов
/ 31 октября 2018

У меня возникла проблема или, точнее, недоразумение о том, как связать табличное представление со значением в Firebase.

Моя информация:

У меня есть Firebase, одна из многих других папок называется «Полеты». В представлении моего приложения я могу добавить некоторую информацию в эту папку по следующему пути: Авиабилеты> userId> autoId> мои интересующие значения, включая дату и некоторые другие String

Мой вопрос:

как я могу добавить в tableView, когда это создается viewDidLoad, одна новая персонализированная ячейка для каждого autoId в моей папке Авиабилеты> userId?

мои попытки:

Я объявляю свой массив:

 var datas: [Flight] = []

Я вызываю viewDidLoad () эту функцию:

func loadFlights() {
    ref = Database.database().reference()
   let userID = Auth.auth().currentUser?.uid
    ref.child("flights").child(userID!).childByAutoId().queryOrderedByKey().observe(.childAdded, with: { (snapshot) in

        if let valueDictionary = snapshot.value as? [AnyHashable:String]
        {

            let date = valueDictionary["Date"]
            let type = valueDictionary["aircraft-model"]
            let registration = valueDictionary["aircraft-registration"]

            let totalTime = valueDictionary["TOTAL-TIME"]

            let depTime = valueDictionary["departure-time"]
            let depPlace = valueDictionary["departure-place"]

            let arrTime = valueDictionary["arrival-time"]
            let arrPlace = valueDictionary["arrival-place"]
            self.datas.append(Flight(from: date ?? "XX-XX-XX", type!, registration!, totalTime!, depTime!, depPlace ?? "NIL", arrTime!, arrPlace!))

            self.tableView.reloadData()
        }else{
            // nothing need to happens
        }
    })

}

наконец, у меня есть часть менеджера таблицы:

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return datas.count
    //return newFlight.count
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "lbCells") as! LogBookCell

    cell.dateLabel.text = datas[indexPath.row].date
    cell.typeLabel.text = datas[indexPath.row].type
    cell.RegistrationLabel.text = datas[indexPath.row].regi

    cell.totalTimeLabel.text = datas[indexPath.row].totalTime

    cell.depTimeLabel.text = datas[indexPath.row].depTime
    cell.depPlaceLabel.text = datas[indexPath.row].depPlace

    cell.arrTimeLabel.text = datas[indexPath.row].arrTime
    cell.arrPlaceLabel.text = datas[indexPath.row].arrPlace

    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete{
        datas.remove(at: indexPath.row)
        tableView.reloadData()
    }
}

И я не понимаю, почему при загрузке страницы tableView в моем приложении ничего не появляется ...

спасибо за вашу помощь!

Флаер-74

Ответы [ 2 ]

0 голосов
/ 31 октября 2018

Вы можете наблюдать значение при добавлении или удалении.

var ref: DatabaseReference! = Database.database().reference()
     ref.child("devices").child(user!.uid).child("device_name").setValue("iPhone test")

let newRef = ref.child("rooms").childByAutoId()
newRef.child("name").setValue("Room test")                                   
                            ref.child("devicesrooms").child(newRef.key).child(user!.uid).setValue(true)

let ev = ref.child("devicesrooms").child(newRef.key)
    var deviceNames = [String: String]()
    var deviceHandles = [String: UInt]()

// Listen for added devices
ev.observe(.childAdded, with: { (snapshot) -> Void in
    // Retrieve device key
    let deviceKey = snapshot.key

    // Add observer on device
    var handle: UInt = 0

    handle = ref.child("devices").child(deviceKey).observe(.value, with: { (snapshot) in
        let value = snapshot.value as? NSDictionary
        let deviceName = value?["device_name"] as? String ?? ""

        // Update or Add deviceName and handle in your dictionary
        deviceNames[deviceKey] = deviceName
        deviceHandles[deviceKey] = handle
    })
})

// Listen for removed devices
ev.observe(.childRemoved, with: { (snapshot) -> Void in
    let deviceKey = snapshot.key

    // Remove deviceName from your dictionary
    deviceNames[deviceKey] = nil

    // Retrieve handle from your dictionary
    if let handle = deviceHandles[deviceKey] {
        // Remove observer on device
        ref.child("devices").child(deviceKey).removeObserverWithHandle(handle)
    }

    // Remove handle from your dictionary
    deviceHandles[deviceKey] = nil
})
0 голосов
/ 31 октября 2018

Где / когда вы настраиваете представление таблицы?

func setUpTable() {
  tableView.delegate = self
  tableView.dataSource = self 
  registerCell(name: "yourcell")
}

Убедитесь, что это перед тем, как позвонить на loadFlights()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...