Я получаю ключ узла, а не дочерний ключ из снимка Swift 4 - PullRequest
0 голосов
/ 02 марта 2019

Я получаю сообщения в узле из базы данных Firebase, но вместо ключа Child я получаю ключ Node, который я буду использовать для удаления записей из базы данных.Строка, где я получаю значение ключа I guard let firebaseKey = snapshot.key as? String else { return }.Я попытался snapshot.children, но у него нет параметра key для выбора.Как мне добраться до этого тогда?Большое спасибо, как обычно.

Th полная функция:

func displayAlerts(setCompletion: @escaping (Bool) -> ()) {
        print("                     MapArray.alertNotificationCoordinatesArray before displayAlert snapshot is: \(MapArray.alertNotificationCoordinatesArray)")
        print("                     self.userAlertNotificationArray before displayAlert snapshot is: \(self.userAlertNotificationArray)")

        if self.userAlertNotificationArray.count == 0 {
           ref = Database.database().reference()

            ref?.child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Community").child("Alert Notifications").observeSingleEvent(of: .value, with: { (snapshot) -> Void in
                print("         snapshot is: \(snapshot)")
                guard let data = snapshot.value as? [String :[String:String]] else { return }

                guard let firebaseKey = snapshot.key as? String else { return }

                data.values.forEach {
//                    let firebaseKey = data.keys[]

                    let dataLatitude = $0["Latitude"]!
                    let dataLongitude = $0["Longitude"]!
                    let type = $0["Description"]!
                    let id = Int($0["Id"]!)

                    print("firebaseKey is:\(firebaseKey)")
                    print("dataLatitude is: \(dataLatitude)")
                    print("dataLongitude is: \(dataLongitude)")
                    print("type is: \(type)")
                    print("id is: \(id)")
                    print("Key is: \(firebaseKey)")
                    print("data is: \(data)")

                    let doubledLatitude = Double(dataLatitude)
                    let doubledLongitude = Double(dataLongitude)
                    let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)

                    let userAlertAnnotation = UserAlert(type: type, coordinate: recombinedCoordinate, firebaseKey: firebaseKey, title: type,id: id!)
                    self.userAlertNotificationArray.append(userAlertAnnotation)  // array of notifications coming from Firebase
                    MapArray.alertNotificationCoordinatesArray.append(recombinedCoordinate)
                }


                            print("Firebase alerts posts retrieved")

                print("                 MapArray.alertNotificationCoordinatesArray after  displayAlert snapshot is: \(MapArray.alertNotificationCoordinatesArray)")
                print("                     self.userAlertNotificationArray after  displayAlert snapshot is: \(self.userAlertNotificationArray)")
                self.mapView.addAnnotations(self.userAlertNotificationArray)
                setCompletion(true)

            })
        }
    }

1 Ответ

0 голосов
/ 02 марта 2019

Я наконец понял, где моя ошибка.Я явно получал родительский ключ.Внутри цикла for in для snapshot.children я объявил переменную для хранения значения снимка потомков, а затем получил мои значения, как и раньше.Я просто не осознавал, что мне нужно было ввести словарь, возвращаемый из Firebase, как снимок, чтобы прочитать записи.Я надеюсь, что это поможет другим начинающим программистам, так как это было для меня большим разочарованием, но, как обычно, обучение трудному пути окупается большим временем.

Итак, полная переписанная функция теперь:

func displayAlerts(setCompletion: @escaping (Bool) -> ()) {
        print("                     MapArray.alertNotificationCoordinatesArray before displayAlert snapshot is: \(MapArray.alertNotificationCoordinatesArray)")
        print("                     self.userAlertNotificationArray before displayAlert snapshot is: \(self.userAlertNotificationArray)")

        if self.userAlertNotificationArray.count == 0 {
            ref = Database.database().reference()

            ref?.child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Community").child("Alert Notifications").observeSingleEvent(of: .value, with: { (snapshot) in
                print("         snapshot is: \(snapshot)")
                guard let data = snapshot.value as? [String :[String:String]] else { return } // checking if the snapshot is the dictonary in the form of [String :[String:String]] else return

                for snap in snapshot.children {
                    let alertSnap = snap as! DataSnapshot  // casting the snapshot children is the dictonary in the form of [String:String]
                    let childrenKey = alertSnap.key
                    let alert = alertSnap.value as! [String:String]
                    let dataLatitude = alert["Latitude"]!
                    let dataLongitude = alert["Longitude"]!
                    let type = alert["Description"]!
                    let id = Int(alert["Id"]!)!
                    print("Node Key is: \(snapshot.key)")
                    print("childrenKey is:\(childrenKey)")
                    print("dataLatitude is: \(String(describing: dataLatitude))")
                    print("dataLongitude is: \(String(describing: dataLongitude))")
                    print("type is: \(String(describing: type))")
                    print("id is: \(String(describing: id))")

                    print("data is: \(data)")

                    let doubledLatitude = Double(dataLatitude)
                    let doubledLongitude = Double(dataLongitude)
                    let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)

                    let userAlertAnnotation = UserAlert(type: type, coordinate: recombinedCoordinate, firebaseKey: childrenKey, title: type,id: id)
                    self.userAlertNotificationArray.append(userAlertAnnotation)  // array of notifications coming from Firebase
                    MapArray.alertNotificationCoordinatesArray.append(recombinedCoordinate)
                }



                print("Firebase alerts posts retrieved")

                print("                 MapArray.alertNotificationCoordinatesArray after  displayAlert snapshot is: \(MapArray.alertNotificationCoordinatesArray)")
                print("                     self.userAlertNotificationArray after  displayAlert snapshot is: \(self.userAlertNotificationArray)")
                self.mapView.addAnnotations(self.userAlertNotificationArray)
                setCompletion(true)

            })
        }
    } 

Одна вещь, которую я не понимаю, тесто - это голосование с понижением, если они хотя бы оставят комментарий, чтобы помочь в улучшении вопросов, это было бы полезно, в противном случае это только усугубляет и без того большое разочарование по поводу того, кого найти.помочь с проблемой, с которой он сталкивается.Надеюсь, что этот последний комментарий также поможет.Это отличное сообщество, и на самом деле я бы не пришел к этому.Это большая гордость быть частью этого.Приветствия.

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