Firebase 查询结果 SWIFT 上的奇怪行为



我在从Firebase检索数据的函数let itemToAdd = snapshot.childSnapshot(forPath: "Shop行上收到此错误。控制台的输出(以 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()

但我仍然得到一个空对象,而不是预期的 [字符串:字符串]。

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

现在我有两种行为:

1st:查询条目并找到 Int:完成的值时,调用了完成,但我没有得到快照打印。2nd:查询条目并查找字符串值时:不会调用完成,但快照会打印带有值的正确条目。

谁能发现这里发生了什么?

我发现问题与我转换查询结果的方式有关。将其转换为 [字符串:字符串] 生成以返回,因为当条目参数的所有值都是字符串时,结果实际上是 [字符串[字符串:字符串]],但是当我将打开时间和关闭时间更改为 Int 时,我必须将快照读取为 [字符串[字符串:任何]]。所以最后一个函数是:

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()

最新更新