Странное поведение в результате запроса Firebase SWIFT - PullRequest
0 голосов
/ 16 января 2019

Я получаю эту ошибку в строке let itemToAdd = snapshot.childSnapshot(forPath: "Shop функция, которая извлекает данные из Firebase.выход консоли в Could not cast value of type 'NSNull' (0x1118c8de0) to 'NSString' (0x10dda45d8)..Я пытаюсь отфильтровать упорядочение базы данных по одному значению opening Time и затем получить другое значение Shop Name из возвращенных записей в снимке.

вот функция:

func filterOpenShops(enterDoStuff: @escaping (Bool) -> ()) {
    ref = Database.database().reference().child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Shops").child("Shops Opening Times")
let query = ref?.queryOrdered(byChild: "Opening Time").queryStarting(atValue: openingTimeQueryStart).queryEnding(atValue: openingTimeQueryEnd)
query?.observe(.value, with: { (snapshot) in
    for childSnapshot in snapshot.children {
        // new modification
        if childSnapshot is DataSnapshot {
            let itemToAdd = snapshot.childSnapshot(forPath: "Shop Name").value as! String // gets the open shop from snapshot
        self.availableShopsArray.append(itemToAdd)
        print(snapshot.children)
         print(" Open Shops are \(self.availableShopsArray)")


        }
    }
    // still asynchronous part
    enterDoStuff(true)
    // call next cascade function filterClosedShops only when data
})

// Sychronous part

print("opening query start is \(openingTimeQueryStart) and opening query end is \(openingTimeQueryEnd)")


} // end of filterOpenShops()

РЕДАКТИРОВАТЬ:

I rewrote the function as:


    func filterOpenShops(enterDoStuff: @escaping (Bool) -> ()) {
        // get from Firebase snapshot all shops opening times into an array of tuples
        //shopOpeningTimeArray:[(storeName: String, weekdayNumber: String, opening1: Sring, closing1: String, opening2:String, closing2: String)]

        ref = Database.database().reference().child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Shops").child("Shops Opening Times")
        let query = ref?.queryOrdered(byChild: "Opening Time").queryStarting(atValue: String(describing: openingTimeQueryStart)).queryEnding(atValue: String(describing :openingTimeQueryEnd))
        query?.observe(.value, with: { (snapshot) in // original is ok
//            guard let data = snapshot.value as? [String:String] else { return }



            for childSnapshot in snapshot.children {

                print("snapshot is: \(childSnapshot)")
                print("snapshot.childrend is: \(snapshot.children)")
                guard let data = snapshot.value as? [String:String] else { return }

                let itemToAdd = data["Shop Name"]
                self.availableShopsArray.append(itemToAdd!)
                print("Open Shop is: \(String(describing: itemToAdd))")
                print(" Open Shops are \(self.availableShopsArray)")



            }
            // still asynchronous part
            enterDoStuff(true)
            // call next cascade function filterClosedShops only when data
            print(" Open Shops are \(self.availableShopsArray)")
        })

        print("opening query start is \(openingTimeQueryStart) and opening query end is \(openingTimeQueryEnd)")


    } // end of filterOpenShops()

но я все еще получаю нулевой объект, а не [String: String], как ожидалось.

Функция, которая создала записи в Firebase:

    func postOpeningTime() {

//        if shopNameTextfield.text != nil && openingTimeTextfield.text != nil && closingTimeTextfield.text != nil {
            let shopName = shopNameTextfield.text!
            let openingTime = openingTimeTextfield.text!
            let closingTime = closingTimeTextfield.text!
//        } else {return}

        let post: [String:String] = [
            "Shop Name" : shopName ,
            "Opening Time" : openingTime ,
            "Closing Time" : closingTime
            ]
        var ref: DatabaseReference!
        ref = Database.database().reference()

        ref?.child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Shops").child("Shops Opening Times").childByAutoId().setValue(post)

    }

Теперь у меня есть два поведения:

1-й: При запросе записей и обнаружении значений, которые Int: завершение вызывается, но я не получаю снимок печати.2-й: при запросе записей и нахождении значений, которые являются String: завершение не вызывается, но снимок выводит правильные записи со значениями.

Может кто-нибудь, пожалуйста, определите, что здесь происходит?

1 Ответ

0 голосов
/ 20 января 2019

Я обнаружил, что проблема в том, как я приводил результат запроса. Приведение его как [String: String] к возвращаемому результату, потому что на самом деле результат был [String [String: String]], когда все значения для параметра записи были String, но так как я изменил Время открытия и Время закрытия на Int, чем я должен читать снимок как [String [String: Any]]. Итак, последняя функция:

func filterOpenShops(setCompletion: @escaping (Bool) -> ()) {
        // Empty the array for beginning of the search
        self.availableShopsArray.removeAll()
        var ref = Database.database().reference()

        ref.child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Shops").child("Shops Opening Times").queryOrdered(byChild: "Opening Time").queryStarting(atValue: openingTimeQueryStart).queryEnding(atValue: openingTimeQueryEnd).observe(.value) { (snapshot) in
            print(snapshot)
            if let data = snapshot.value as? [String : [String : Any]] {
                for (_, value) in
                    data {
                        let shopName = value["Shop Name"] as! String
                        let active = value["Active"] as! String
                        if active == "true" {
                            self.availableShopsArray.append(shopName)
                            print("Shop_Name is :\(shopName)")
                            print("self.availableShopsArray is: \(self.availableShopsArray)")
                        }
                }

            } else {
                print("No Shops")
            }
            // still asynchronous part
            setCompletion(true)
            // call next cascade function filterClosedShops only when data retrieving is finished
            self.filterClosedShops(setCompletion: self.completionSetter)

            print("  1 Open Shops are \(self.availableShopsArray)")
        }
    } // end of filterOpenShops()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...