How to handle timeout in queries with Firebase

前端 未结 5 1679
终归单人心
终归单人心 2021-01-02 04:35

I noticed that if I execute a query in Firebase and the database server is not reachable, the callback waits just forever (or until the server is reachable again).

W

5条回答
  •  伪装坚强ぢ
    2021-01-02 04:52

    Here's my solution for the Firebase iOS SDK, this may be helpful for others:

    extension DatabaseReference {
    
        func observe(_ eventType: DataEventType, timeout: TimeInterval, with block: @escaping (DataSnapshot?) -> Void) -> UInt {
    
            var handle: UInt!
    
            let timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false) { (_) in
                self.removeObserver(withHandle: handle)
                block(nil)
            }
    
            handle = observe(eventType) { (snapshot) in
                timer.invalidate()
                block(snapshot)
            }
    
            return handle
        }
    
    }
    

    Usage:

    database.child("users").observe(.value, timeout: 30) { (snapshot) in
    
        guard let snapshot = snapshot else {
            // Timeout!
            return
        }
    
        // We got data within the timeout, so do something with snapshot.value
    }
    

提交回复
热议问题