离线时,Firebase值事件不会一直触发

Nic*_*ico 15 ios firebase swift firebase-realtime-database

我有以下路径模式:

/ID_Company/boxes/timestamp_of_the_day/ID_box
Run Code Online (Sandbox Code Playgroud)

假设我刚开始新的一天,我就离线了.就在Firebase DB上,路径/ID_Company/boxes/timestamp_of_TODAY不存在,也不存在于缓存中.

不,我在路径中添加了一个新框 /ID_Company/boxes/timestamp_of_TODAY/id_box1

如果我有一个关于childAdded事件的观察者,它将被触发.但如果我有一个关于value事件的观察者,则不会触发任何事情.

现在让我说,当我添加第一个框时,我在线.所以在firebase上这条路径/ID_Company/boxes/timestamp_of_TODAY/id_box1存在,因此它在本地运行.

它离线了.然后我添加一个新框/ID_Company/boxes/timestamp_of_TODAY/id_box2,然后'value`事件被触发,我只是不明白为什么.

为什么在timestamp_of_TODAY已经存在的情况下触发,但在不存在时触发?

谢谢你的帮助.

编辑:

以下是我添加方框的方法:

        guard let startingTimestamp = date.beginning(of: .day)?.timeIntervalSince1970 else { return nil }

        let boxRef = dbRef.child("ID_Company").child("boxes").child("\(startingTimestamp)").childByAutoId()

        var box = box
        box.id = boxRef.key

        boxRef.setValue(box.toDictionary()) { error, ref in
            if let error = error as? NSError {
                print(error)
                completion(error)
            } else {
                completion(nil)
            }
        }
Run Code Online (Sandbox Code Playgroud)

以下是我如何获得盒子:

    guard let startingTimestamp = day.beginning(of: .day)?.timeIntervalSince1970, let endingTimestamp = day.end(of: .day)?.timeIntervalSince1970 else { return nil }

    let boxesRef = dbRef.child("ID_Company").child("boxes").child("\(startingTimestamp)")

    let query = boxesRef.queryOrdered(byChild: Box.Key.dateTimestamp.rawValue).queryStarting(atValue: startingTimestamp).queryEnding(atValue: endingTimestamp + 0.001)

    let handle = query.observe(.value, with: { snapshot in
        var boxes: [Box] = []

        for child in snapshot.children {
            let box = Box(snapshot: child as! FIRDataSnapshot)

            if userID == nil || box.userID == userID! {
                boxes.append(box)
            }
        }

        completion(boxes.reversed())
    })
Run Code Online (Sandbox Code Playgroud)

Hit*_*esh 0

我确定,但请尝试下面。可能适合你。

守卫 让startingTimestamp = day.beginning(of: .day)?.timeIntervalSince1970, 让endingTimestamp = day.end(of: .day)?.timeIntervalSince1970 else { return nil }

let boxesRef = dbRef.child("ID_Company").child("boxes").child("\(startingTimestamp)")

let query = boxesRef.queryOrdered(byChild: Box.Key.dateTimestamp.rawValue).queryStarting(atValue: startingTimestamp).queryEnding(atValue: endingTimestamp + 0.001)

let handle = query.observe(.ChildAdded, with: { snapshot in
    var boxes: [Box] = []

    for child in snapshot.children {
        let box = Box(snapshot: child as! FIRDataSnapshot)

        if userID == nil || box.userID == userID! {
            boxes.append(box)
        }
    }

    completion(boxes.reversed())
})
Run Code Online (Sandbox Code Playgroud)